automatic project update

This commit is contained in:
Julien Dubois 2016-10-28 14:51:05 +02:00
parent b62fd1d51c
commit f5396338dd
50 changed files with 149 additions and 1756 deletions

32
.gitignore vendored
View File

@ -6,14 +6,14 @@
######################
# Node
######################
/node/**
/node_tmp/**
/node_modules/**
node/
node_tmp/
node_modules/
######################
# SASS
######################
.sass-cache/**
.sass-cache/
######################
# Eclipse
@ -21,15 +21,15 @@
*.pydevproject
.project
.metadata
/tmp/**
/tmp/**/*
tmp/
tmp/**/*
*.tmp
*.bak
*.swp
*~.nib
local.properties
.classpath
.settings/**
.settings/
.loadpath
/src/main/resources/rebel.xml
@ -48,7 +48,7 @@ local.properties
######################
# Intellij
######################
.idea/**
.idea/
*.iml
*.iws
*.ipr
@ -58,18 +58,18 @@ local.properties
######################
# Visual Studio Code
######################
.vscode/**
.vscode/
######################
# Maven
######################
/log/**
/target/**
log/
target/
######################
# Gradle
######################
.gradle/**
.gradle/
######################
# Package Files
@ -104,10 +104,10 @@ Desktop.ini
######################
# Directories
######################
/build/**
/bin/**
/spring_loaded/**
/deploy/**
build/
bin/
spring_loaded/
deploy/
######################
# Logs

View File

@ -24,7 +24,7 @@
"en"
],
"serverPort": 8080,
"jhipsterVersion": "3.9.1",
"jhipsterVersion": "3.10.0",
"enableSocialSignIn": false,
"useSass": false,
"jhiPrefix": "jhi",

View File

@ -22,6 +22,7 @@ module.exports = {
function app() {
return gulp.src(config.app + 'index.html')
.pipe(inject(gulp.src(config.app + 'app/**/*.js')
.pipe(plumber({errorHandler: handleErrors}))
.pipe(naturalSort())
.pipe(angularFilesort()), {relative: true}))
.pipe(gulp.dest(config.app));

View File

@ -1,4 +1,4 @@
// Generated on 2016-10-11 using generator-jhipster 3.9.1
// Generated on 2016-10-28 using generator-jhipster 3.10.0
'use strict';
var gulp = require('gulp'),

View File

@ -14,7 +14,7 @@
"eslint-config-angular": "0.5.0",
"eslint-plugin-angular": "1.3.1",
"event-stream": "3.3.4",
"generator-jhipster": "3.9.1",
"generator-jhipster": "3.10.0",
"gulp": "3.9.1",
"gulp-angular-filesort": "1.1.1",
"gulp-angular-templatecache": "2.0.0",

20
pom.xml
View File

@ -46,7 +46,7 @@
<metrics-spring.version>3.1.3</metrics-spring.version>
<logstash-logback-encoder.version>4.7</logstash-logback-encoder.version>
<run.addResources>false</run.addResources>
<spring-security.version>4.1.0.RELEASE</spring-security.version>
<spring-security.version>4.1.3.RELEASE</spring-security.version>
<springfox.version>2.5.0</springfox.version>
<!-- Sonar properties -->
<project.testresult.directory>${project.build.directory}/test-results</project.testresult.directory>
@ -163,6 +163,11 @@
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-bean-validators</artifactId>
<version>${springfox.version}</version>
</dependency>
<dependency>
<groupId>com.mattbertolini</groupId>
<artifactId>liquibase-slf4j</artifactId>
@ -214,7 +219,6 @@
<version>${gatling.version}</version>
<scope>test</scope>
</dependency>
<!-- include netty handler explicitly to overcome dependency mismatch when using cassandra -->
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
@ -355,16 +359,8 @@
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-cloudfoundry-connector</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-spring-service-connector</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-localconfig-connector</artifactId>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cloud-connectors</artifactId>
</dependency>
<!-- security -->
<dependency>

View File

@ -9,16 +9,13 @@ import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.*;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.util.Assert;
import javax.annotation.PreDestroy;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.metamodel.EntityType;
import javax.persistence.metamodel.PluralAttribute;
import java.util.Set;
import java.util.SortedSet;
import java.util.stream.Stream;
@SuppressWarnings("unused")
@Configuration
@ -51,30 +48,12 @@ public class CacheConfiguration {
cacheManager = net.sf.ehcache.CacheManager.create();
cacheManager.getConfiguration().setMaxBytesLocalHeap(jHipsterProperties.getCache().getEhcache().getMaxBytesLocalHeap());
log.debug("Registering Ehcache Metrics gauges");
Set<EntityType<?>> entities = entityManager.getMetamodel().getEntities();
for (EntityType<?> entity : entities) {
String name = entity.getName();
if (name == null || entity.getJavaType() != null) {
name = entity.getJavaType().getName();
}
Assert.notNull(name, "entity cannot exist without an identifier");
reconfigureCache(name, jHipsterProperties);
for (PluralAttribute pluralAttribute : entity.getPluralAttributes()) {
reconfigureCache(name + "." + pluralAttribute.getName(), jHipsterProperties);
}
}
Stream.of(cacheManager.getCacheNames()).forEach(name -> {
net.sf.ehcache.Cache cache = cacheManager.getCache(name);
cacheManager.replaceCacheWithDecoratedCache(cache, InstrumentedEhcache.instrument(metricRegistry, cache));
});
EhCacheCacheManager ehCacheManager = new EhCacheCacheManager();
ehCacheManager.setCacheManager(cacheManager);
return ehCacheManager;
}
private void reconfigureCache(String name, JHipsterProperties jHipsterProperties) {
net.sf.ehcache.Cache cache = cacheManager.getCache(name);
if (cache != null) {
cache.getCacheConfiguration().setTimeToLiveSeconds(jHipsterProperties.getCache().getTimeToLiveSeconds());
net.sf.ehcache.Ehcache decoratedCache = InstrumentedEhcache.instrument(metricRegistry, cache);
cacheManager.replaceCacheWithDecoratedCache(cache, decoratedCache);
}
}
}

View File

@ -14,7 +14,7 @@ public final class DefaultProfileUtil {
private static final String SPRING_PROFILE_DEFAULT = "spring.profiles.default";
private DefaultProfileUtil(){
private DefaultProfileUtil() {
}
/**

View File

@ -124,19 +124,8 @@ public class JHipsterProperties {
}
public static class Cache {
private int timeToLiveSeconds = 3600;
private final Ehcache ehcache = new Ehcache();
public int getTimeToLiveSeconds() {
return timeToLiveSeconds;
}
public void setTimeToLiveSeconds(int timeToLiveSeconds) {
this.timeToLiveSeconds = timeToLiveSeconds;
}
public Ehcache getEhcache() {
return ehcache;
}

View File

@ -1,7 +1,10 @@
package io.github.jhipster.sample.config;
import ch.qos.logback.classic.AsyncAppender;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.spi.LoggerContextListener;
import ch.qos.logback.core.spi.ContextAwareBase;
import net.logstash.logback.appender.LogstashSocketAppender;
import net.logstash.logback.stacktrace.ShortenedThrowableConverter;
import org.slf4j.Logger;
@ -32,11 +35,16 @@ public class LoggingConfiguration {
@PostConstruct
private void init() {
if (jHipsterProperties.getLogging().getLogstash().isEnabled()) {
addLogstashAppender();
addLogstashAppender(context);
// Add context listener
LogbackLoggerContextListener loggerContextListener = new LogbackLoggerContextListener();
loggerContextListener.setContext(context);
context.addListener(loggerContextListener);
}
}
public void addLogstashAppender() {
public void addLogstashAppender(LoggerContext context) {
log.info("Initializing Logstash logging");
LogstashSocketAppender logstashAppender = new LogstashSocketAppender();
@ -67,4 +75,37 @@ public class LoggingConfiguration {
context.getLogger("ROOT").addAppender(asyncLogstashAppender);
}
/**
* Logback configuration is achieved by configuration file and API.
* When configuration file change is detected, the configuration is reset.
* This listener ensures that the programmatic configuration is also re-applied after reset.
*/
class LogbackLoggerContextListener extends ContextAwareBase implements LoggerContextListener {
@Override
public boolean isResetResistant() {
return true;
}
@Override
public void onStart(LoggerContext context) {
addLogstashAppender(context);
}
@Override
public void onReset(LoggerContext context) {
addLogstashAppender(context);
}
@Override
public void onStop(LoggerContext context) {
}
@Override
public void onLevelChange(ch.qos.logback.classic.Logger logger, Level level) {
}
}
}

View File

@ -1,7 +1,6 @@
package io.github.jhipster.sample.config;
import io.github.jhipster.sample.security.*;
import io.github.jhipster.sample.web.filter.CsrfCookieGeneratorFilter;
import io.github.jhipster.sample.config.JHipsterProperties;
import org.springframework.beans.factory.BeanInitializationException;
@ -19,7 +18,7 @@ import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.data.repository.query.SecurityEvaluationContextExtension;
import org.springframework.security.web.authentication.RememberMeServices;
import org.springframework.security.web.csrf.CsrfFilter;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import javax.inject.Inject;
@ -82,10 +81,9 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.and()
.addFilterAfter(new CsrfCookieGeneratorFilter(), CsrfFilter.class)
.exceptionHandling()
.accessDeniedHandler(new CustomAccessDeniedHandler())
.authenticationEntryPoint(authenticationEntryPoint)
.and()
.rememberMe()
@ -104,7 +102,6 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
.logout()
.logoutUrl("/api/logout")
.logoutSuccessHandler(ajaxLogoutSuccessHandler)
.deleteCookies("JSESSIONID", "CSRF-TOKEN")
.permitAll()
.and()
.headers()

View File

@ -28,6 +28,7 @@ import static springfox.documentation.builders.PathSelectors.regex;
*/
@Configuration
@EnableSwagger2
@Import(springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration.class)
@Profile(Constants.SPRING_PROFILE_SWAGGER)
public class SwaggerConfiguration {

View File

@ -26,8 +26,6 @@ public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findOneByLogin(String login);
Optional<User> findOneById(Long userId);
@Query(value = "select distinct user from User user left join fetch user.authorities",
countQuery = "select count(user) from User user")
Page<User> findAllWithAuthorities(Pageable pageable);

View File

@ -1,56 +0,0 @@
package io.github.jhipster.sample.security;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.access.AccessDeniedHandlerImpl;
import org.springframework.security.web.csrf.CsrfException;
/**
* An implementation of AccessDeniedHandler by wrapping the AccessDeniedHandlerImpl.
*
* In addition to sending a 403 (SC_FORBIDDEN) HTTP error code, it will remove the invalid CSRF cookie from the browser
* side when a CsrfException occurs. In this way the browser side application, e.g. JavaScript code, can
* distinguish the CsrfException from other AccessDeniedExceptions and perform more specific operations. For instance,
* send a GET HTTP method to obtain a new CSRF token.
*
* @see AccessDeniedHandlerImpl
*/
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
private AccessDeniedHandlerImpl accessDeniedHandlerImpl = new AccessDeniedHandlerImpl();
public void handle(HttpServletRequest request, HttpServletResponse response,
AccessDeniedException accessDeniedException) throws IOException, ServletException {
if (accessDeniedException instanceof CsrfException && !response.isCommitted()) {
// Remove the session cookie so that client knows it's time to obtain a new CSRF token
String pCookieName = "CSRF-TOKEN";
Cookie cookie = new Cookie(pCookieName, "");
cookie.setMaxAge(0);
cookie.setHttpOnly(false);
cookie.setPath("/");
response.addCookie(cookie);
}
accessDeniedHandlerImpl.handle(request, response, accessDeniedException);
}
/**
* The error page to use. Must begin with a "/" and is interpreted relative to the current context root.
*
* @param errorPage the dispatcher path to display
*
* @throws IllegalArgumentException if the argument doesn't comply with the above limitations
* @see AccessDeniedHandlerImpl#setErrorPage(String)
*/
public void setErrorPage(String errorPage) {
accessDeniedHandlerImpl.setErrorPage(errorPage);
}
}

View File

@ -150,8 +150,8 @@ public class UserService {
public void updateUser(Long id, String login, String firstName, String lastName, String email,
boolean activated, String langKey, Set<String> authorities) {
userRepository
.findOneById(id)
Optional.of(userRepository
.findOne(id))
.ifPresent(u -> {
u.setLogin(login);
u.setFirstName(firstName);

View File

@ -1,36 +0,0 @@
package io.github.jhipster.sample.web.filter;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Filter used to put the CSRF token generated by Spring Security in a cookie for use by AngularJS.
*/
public class CsrfCookieGeneratorFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
// Spring put the CSRF token in session attribute "_csrf"
CsrfToken csrfToken = (CsrfToken) request.getAttribute("_csrf");
// Send the cookie only if the token has changed
String actualToken = request.getHeader("X-CSRF-TOKEN");
if (actualToken == null || !actualToken.equals(csrfToken.getToken())) {
// Session cookie that will be used by AngularJS
String pCookieName = "CSRF-TOKEN";
Cookie cookie = new Cookie(pCookieName, csrfToken.getToken());
cookie.setMaxAge(-1);
cookie.setHttpOnly(false);
cookie.setPath("/");
response.addCookie(cookie);
}
filterChain.doFilter(request, response);
}
}

View File

@ -58,8 +58,7 @@ public class AccountResource {
* @param request the HTTP request
* @return the ResponseEntity with status 201 (Created) if the user is registered or 400 (Bad Request) if the login or e-mail is already in use
*/
@RequestMapping(value = "/register",
method = RequestMethod.POST,
@PostMapping(path = "/register",
produces={MediaType.APPLICATION_JSON_VALUE, MediaType.TEXT_PLAIN_VALUE})
@Timed
public ResponseEntity<?> registerAccount(@Valid @RequestBody ManagedUserVM managedUserVM, HttpServletRequest request) {
@ -94,9 +93,7 @@ public class AccountResource {
* @param key the activation key
* @return the ResponseEntity with status 200 (OK) and the activated user in body, or status 500 (Internal Server Error) if the user couldn't be activated
*/
@RequestMapping(value = "/activate",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@GetMapping("/activate")
@Timed
public ResponseEntity<String> activateAccount(@RequestParam(value = "key") String key) {
return userService.activateRegistration(key)
@ -110,9 +107,7 @@ public class AccountResource {
* @param request the HTTP request
* @return the login if the user is authenticated
*/
@RequestMapping(value = "/authenticate",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@GetMapping("/authenticate")
@Timed
public String isAuthenticated(HttpServletRequest request) {
log.debug("REST request to check if the current user is authenticated");
@ -124,9 +119,7 @@ public class AccountResource {
*
* @return the ResponseEntity with status 200 (OK) and the current user in body, or status 500 (Internal Server Error) if the user couldn't be returned
*/
@RequestMapping(value = "/account",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@GetMapping("/account")
@Timed
public ResponseEntity<UserDTO> getAccount() {
return Optional.ofNullable(userService.getUserWithAuthorities())
@ -140,9 +133,7 @@ public class AccountResource {
* @param userDTO the current user information
* @return the ResponseEntity with status 200 (OK), or status 400 (Bad Request) or 500 (Internal Server Error) if the user couldn't be updated
*/
@RequestMapping(value = "/account",
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
@PostMapping("/account")
@Timed
public ResponseEntity<String> saveAccount(@Valid @RequestBody UserDTO userDTO) {
Optional<User> existingUser = userRepository.findOneByEmail(userDTO.getEmail());
@ -165,8 +156,7 @@ public class AccountResource {
* @param password the new password
* @return the ResponseEntity with status 200 (OK), or status 400 (Bad Request) if the new password is not strong enough
*/
@RequestMapping(value = "/account/change_password",
method = RequestMethod.POST,
@PostMapping(path = "/account/change_password",
produces = MediaType.TEXT_PLAIN_VALUE)
@Timed
public ResponseEntity<?> changePassword(@RequestBody String password) {
@ -183,9 +173,7 @@ public class AccountResource {
* @return the ResponseEntity with status 200 (OK) and the current open sessions in body,
* or status 500 (Internal Server Error) if the current open sessions couldn't be retrieved
*/
@RequestMapping(value = "/account/sessions",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@GetMapping("/account/sessions")
@Timed
public ResponseEntity<List<PersistentToken>> getCurrentSessions() {
return userRepository.findOneByLogin(SecurityUtils.getCurrentUserLogin())
@ -211,8 +199,7 @@ public class AccountResource {
* @param series the series of an existing session
* @throws UnsupportedEncodingException if the series couldnt be URL decoded
*/
@RequestMapping(value = "/account/sessions/{series}",
method = RequestMethod.DELETE)
@DeleteMapping("/account/sessions/{series}")
@Timed
public void invalidateSession(@PathVariable String series) throws UnsupportedEncodingException {
String decodedSeries = URLDecoder.decode(series, "UTF-8");
@ -230,8 +217,7 @@ public class AccountResource {
* @param request the HTTP request
* @return the ResponseEntity with status 200 (OK) if the e-mail was sent, or status 400 (Bad Request) if the e-mail address is not registered
*/
@RequestMapping(value = "/account/reset_password/init",
method = RequestMethod.POST,
@PostMapping(path = "/account/reset_password/init",
produces = MediaType.TEXT_PLAIN_VALUE)
@Timed
public ResponseEntity<?> requestPasswordReset(@RequestBody String mail, HttpServletRequest request) {
@ -255,8 +241,7 @@ public class AccountResource {
* @return the ResponseEntity with status 200 (OK) if the password has been reset,
* or status 400 (Bad Request) or 500 (Internal Server Error) if the password could not be reset
*/
@RequestMapping(value = "/account/reset_password/finish",
method = RequestMethod.POST,
@PostMapping(path = "/account/reset_password/finish",
produces = MediaType.TEXT_PLAIN_VALUE)
@Timed
public ResponseEntity<String> finishPasswordReset(@RequestBody KeyAndPasswordVM keyAndPassword) {

View File

@ -8,7 +8,6 @@ import org.springframework.boot.actuate.audit.AuditEvent;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpHeaders;
@ -22,7 +21,7 @@ import java.util.List;
* REST controller for getting the audit events.
*/
@RestController
@RequestMapping(value = "/management/jhipster/audits", produces = MediaType.APPLICATION_JSON_VALUE)
@RequestMapping("/management/jhipster/audits")
public class AuditResource {
private AuditEventService auditEventService;
@ -39,7 +38,7 @@ public class AuditResource {
* @return the ResponseEntity with status 200 (OK) and the list of AuditEvents in body
* @throws URISyntaxException if there is an error to generate the pagination HTTP headers
*/
@RequestMapping(method = RequestMethod.GET)
@GetMapping
public ResponseEntity<List<AuditEvent>> getAll(Pageable pageable) throws URISyntaxException {
Page<AuditEvent> page = auditEventService.findAll(pageable);
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/audits");
@ -56,8 +55,7 @@ public class AuditResource {
* @throws URISyntaxException if there is an error to generate the pagination HTTP headers
*/
@RequestMapping(method = RequestMethod.GET,
params = {"fromDate", "toDate"})
@GetMapping(params = {"fromDate", "toDate"})
public ResponseEntity<List<AuditEvent>> getByDates(
@RequestParam(value = "fromDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate fromDate,
@RequestParam(value = "toDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate toDate,
@ -74,8 +72,7 @@ public class AuditResource {
* @param id the id of the entity to get
* @return the ResponseEntity with status 200 (OK) and the AuditEvent in body, or status 404 (Not Found)
*/
@RequestMapping(value = "/{id:.+}",
method = RequestMethod.GET)
@GetMapping("/{id:.+}")
public ResponseEntity<AuditEvent> get(@PathVariable Long id) {
return auditEventService.find(id)
.map((entity) -> new ResponseEntity<>(entity, HttpStatus.OK))

View File

@ -9,7 +9,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@ -39,9 +38,7 @@ public class BankAccountResource {
* @return the ResponseEntity with status 201 (Created) and with body the new bankAccount, or with status 400 (Bad Request) if the bankAccount has already an ID
* @throws URISyntaxException if the Location URI syntax is incorrect
*/
@RequestMapping(value = "/bank-accounts",
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
@PostMapping("/bank-accounts")
@Timed
public ResponseEntity<BankAccount> createBankAccount(@Valid @RequestBody BankAccount bankAccount) throws URISyntaxException {
log.debug("REST request to save BankAccount : {}", bankAccount);
@ -63,9 +60,7 @@ public class BankAccountResource {
* or with status 500 (Internal Server Error) if the bankAccount couldnt be updated
* @throws URISyntaxException if the Location URI syntax is incorrect
*/
@RequestMapping(value = "/bank-accounts",
method = RequestMethod.PUT,
produces = MediaType.APPLICATION_JSON_VALUE)
@PutMapping("/bank-accounts")
@Timed
public ResponseEntity<BankAccount> updateBankAccount(@Valid @RequestBody BankAccount bankAccount) throws URISyntaxException {
log.debug("REST request to update BankAccount : {}", bankAccount);
@ -83,9 +78,7 @@ public class BankAccountResource {
*
* @return the ResponseEntity with status 200 (OK) and the list of bankAccounts in body
*/
@RequestMapping(value = "/bank-accounts",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@GetMapping("/bank-accounts")
@Timed
public List<BankAccount> getAllBankAccounts() {
log.debug("REST request to get all BankAccounts");
@ -99,9 +92,7 @@ public class BankAccountResource {
* @param id the id of the bankAccount to retrieve
* @return the ResponseEntity with status 200 (OK) and with body the bankAccount, or with status 404 (Not Found)
*/
@RequestMapping(value = "/bank-accounts/{id}",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@GetMapping("/bank-accounts/{id}")
@Timed
public ResponseEntity<BankAccount> getBankAccount(@PathVariable Long id) {
log.debug("REST request to get BankAccount : {}", id);
@ -119,9 +110,7 @@ public class BankAccountResource {
* @param id the id of the bankAccount to delete
* @return the ResponseEntity with status 200 (OK)
*/
@RequestMapping(value = "/bank-accounts/{id}",
method = RequestMethod.DELETE,
produces = MediaType.APPLICATION_JSON_VALUE)
@DeleteMapping("/bank-accounts/{id}")
@Timed
public ResponseEntity<Void> deleteBankAccount(@PathVariable Long id) {
log.debug("REST request to delete BankAccount : {}", id);

View File

@ -9,7 +9,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@ -39,9 +38,7 @@ public class LabelResource {
* @return the ResponseEntity with status 201 (Created) and with body the new label, or with status 400 (Bad Request) if the label has already an ID
* @throws URISyntaxException if the Location URI syntax is incorrect
*/
@RequestMapping(value = "/labels",
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
@PostMapping("/labels")
@Timed
public ResponseEntity<Label> createLabel(@Valid @RequestBody Label label) throws URISyntaxException {
log.debug("REST request to save Label : {}", label);
@ -63,9 +60,7 @@ public class LabelResource {
* or with status 500 (Internal Server Error) if the label couldnt be updated
* @throws URISyntaxException if the Location URI syntax is incorrect
*/
@RequestMapping(value = "/labels",
method = RequestMethod.PUT,
produces = MediaType.APPLICATION_JSON_VALUE)
@PutMapping("/labels")
@Timed
public ResponseEntity<Label> updateLabel(@Valid @RequestBody Label label) throws URISyntaxException {
log.debug("REST request to update Label : {}", label);
@ -83,9 +78,7 @@ public class LabelResource {
*
* @return the ResponseEntity with status 200 (OK) and the list of labels in body
*/
@RequestMapping(value = "/labels",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@GetMapping("/labels")
@Timed
public List<Label> getAllLabels() {
log.debug("REST request to get all Labels");
@ -99,9 +92,7 @@ public class LabelResource {
* @param id the id of the label to retrieve
* @return the ResponseEntity with status 200 (OK) and with body the label, or with status 404 (Not Found)
*/
@RequestMapping(value = "/labels/{id}",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@GetMapping("/labels/{id}")
@Timed
public ResponseEntity<Label> getLabel(@PathVariable Long id) {
log.debug("REST request to get Label : {}", id);
@ -119,9 +110,7 @@ public class LabelResource {
* @param id the id of the label to delete
* @return the ResponseEntity with status 200 (OK)
*/
@RequestMapping(value = "/labels/{id}",
method = RequestMethod.DELETE,
produces = MediaType.APPLICATION_JSON_VALUE)
@DeleteMapping("/labels/{id}")
@Timed
public ResponseEntity<Void> deleteLabel(@PathVariable Long id) {
log.debug("REST request to delete Label : {}", id);

View File

@ -7,7 +7,6 @@ import ch.qos.logback.classic.LoggerContext;
import com.codahale.metrics.annotation.Timed;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@ -20,9 +19,7 @@ import java.util.stream.Collectors;
@RequestMapping("/management/jhipster")
public class LogsResource {
@RequestMapping(value = "/logs",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@GetMapping("/logs")
@Timed
public List<LoggerVM> getList() {
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
@ -32,8 +29,7 @@ public class LogsResource {
.collect(Collectors.toList());
}
@RequestMapping(value = "/logs",
method = RequestMethod.PUT)
@PutMapping("/logs")
@ResponseStatus(HttpStatus.NO_CONTENT)
@Timed
public void changeLevel(@RequestBody LoggerVM jsonLogger) {

View File

@ -12,7 +12,6 @@ import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@ -42,9 +41,7 @@ public class OperationResource {
* @return the ResponseEntity with status 201 (Created) and with body the new operation, or with status 400 (Bad Request) if the operation has already an ID
* @throws URISyntaxException if the Location URI syntax is incorrect
*/
@RequestMapping(value = "/operations",
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
@PostMapping("/operations")
@Timed
public ResponseEntity<Operation> createOperation(@Valid @RequestBody Operation operation) throws URISyntaxException {
log.debug("REST request to save Operation : {}", operation);
@ -66,9 +63,7 @@ public class OperationResource {
* or with status 500 (Internal Server Error) if the operation couldnt be updated
* @throws URISyntaxException if the Location URI syntax is incorrect
*/
@RequestMapping(value = "/operations",
method = RequestMethod.PUT,
produces = MediaType.APPLICATION_JSON_VALUE)
@PutMapping("/operations")
@Timed
public ResponseEntity<Operation> updateOperation(@Valid @RequestBody Operation operation) throws URISyntaxException {
log.debug("REST request to update Operation : {}", operation);
@ -88,9 +83,7 @@ public class OperationResource {
* @return the ResponseEntity with status 200 (OK) and the list of operations in body
* @throws URISyntaxException if there is an error to generate the pagination HTTP headers
*/
@RequestMapping(value = "/operations",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@GetMapping("/operations")
@Timed
public ResponseEntity<List<Operation>> getAllOperations(Pageable pageable)
throws URISyntaxException {
@ -106,9 +99,7 @@ public class OperationResource {
* @param id the id of the operation to retrieve
* @return the ResponseEntity with status 200 (OK) and with body the operation, or with status 404 (Not Found)
*/
@RequestMapping(value = "/operations/{id}",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@GetMapping("/operations/{id}")
@Timed
public ResponseEntity<Operation> getOperation(@PathVariable Long id) {
log.debug("REST request to get Operation : {}", id);
@ -126,9 +117,7 @@ public class OperationResource {
* @param id the id of the operation to delete
* @return the ResponseEntity with status 200 (OK)
*/
@RequestMapping(value = "/operations/{id}",
method = RequestMethod.DELETE,
produces = MediaType.APPLICATION_JSON_VALUE)
@DeleteMapping("/operations/{id}")
@Timed
public ResponseEntity<Void> deleteOperation(@PathVariable Long id) {
log.debug("REST request to delete Operation : {}", id);

View File

@ -3,10 +3,7 @@ package io.github.jhipster.sample.web.rest;
import io.github.jhipster.sample.config.DefaultProfileUtil;
import io.github.jhipster.sample.config.JHipsterProperties;
import org.springframework.core.env.Environment;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import javax.inject.Inject;
import java.util.ArrayList;
@ -23,9 +20,7 @@ public class ProfileInfoResource {
@Inject
private JHipsterProperties jHipsterProperties;
@RequestMapping(value = "/profile-info",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@GetMapping("/profile-info")
public ProfileInfoResponse getActiveProfiles() {
return new ProfileInfoResponse(DefaultProfileUtil.getActiveProfiles(env), getRibbonEnv());
}

View File

@ -16,7 +16,6 @@ import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.*;
@ -80,9 +79,7 @@ public class UserResource {
* @return the ResponseEntity with status 201 (Created) and with body the new user, or with status 400 (Bad Request) if the login or email is already in use
* @throws URISyntaxException if the Location URI syntax is incorrect
*/
@RequestMapping(value = "/users",
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
@PostMapping("/users")
@Timed
@Secured(AuthoritiesConstants.ADMIN)
public ResponseEntity<?> createUser(@RequestBody ManagedUserVM managedUserVM, HttpServletRequest request) throws URISyntaxException {
@ -120,9 +117,7 @@ public class UserResource {
* or with status 400 (Bad Request) if the login or email is already in use,
* or with status 500 (Internal Server Error) if the user couldn't be updated
*/
@RequestMapping(value = "/users",
method = RequestMethod.PUT,
produces = MediaType.APPLICATION_JSON_VALUE)
@PutMapping("/users")
@Timed
@Secured(AuthoritiesConstants.ADMIN)
public ResponseEntity<ManagedUserVM> updateUser(@RequestBody ManagedUserVM managedUserVM) {
@ -151,9 +146,7 @@ public class UserResource {
* @return the ResponseEntity with status 200 (OK) and with body all users
* @throws URISyntaxException if the pagination headers couldn't be generated
*/
@RequestMapping(value = "/users",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@GetMapping("/users")
@Timed
public ResponseEntity<List<ManagedUserVM>> getAllUsers(Pageable pageable)
throws URISyntaxException {
@ -171,9 +164,7 @@ public class UserResource {
* @param login the login of the user to find
* @return the ResponseEntity with status 200 (OK) and with body the "login" user, or with status 404 (Not Found)
*/
@RequestMapping(value = "/users/{login:" + Constants.LOGIN_REGEX + "}",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@GetMapping("/users/{login:" + Constants.LOGIN_REGEX + "}")
@Timed
public ResponseEntity<ManagedUserVM> getUser(@PathVariable String login) {
log.debug("REST request to get User : {}", login);
@ -189,9 +180,7 @@ public class UserResource {
* @param login the login of the user to delete
* @return the ResponseEntity with status 200 (OK)
*/
@RequestMapping(value = "/users/{login:" + Constants.LOGIN_REGEX + "}",
method = RequestMethod.DELETE,
produces = MediaType.APPLICATION_JSON_VALUE)
@DeleteMapping("/users/{login:" + Constants.LOGIN_REGEX + "}")
@Timed
@Secured(AuthoritiesConstants.ADMIN)
public ResponseEntity<Void> deleteUser(@PathVariable String login) {

View File

@ -11,7 +11,7 @@ public final class HeaderUtil {
private static final Logger log = LoggerFactory.getLogger(HeaderUtil.class);
private HeaderUtil(){
private HeaderUtil() {
}
public static HttpHeaders createAlert(String message, String param) {

View File

@ -15,7 +15,7 @@ import java.net.URISyntaxException;
*/
public final class PaginationUtil {
private PaginationUtil(){
private PaginationUtil() {
}
public static HttpHeaders generatePaginationHttpHeaders(Page<?> page, String baseUrl)

View File

@ -62,7 +62,6 @@ server:
jhipster:
cache: # Hibernate 2nd level cache, used by CacheConfiguration
timeToLiveSeconds: 3600
ehcache:
maxBytesLocalHeap: 16M
security:

View File

@ -65,7 +65,6 @@ jhipster:
cache: # Used by the CachingHttpHeadersFilter
timeToLiveInDays: 1461
cache: # Hibernate 2nd level cache, used by CacheConfiguration
timeToLiveSeconds: 3600
ehcache:
maxBytesLocalHeap: 256M
security:

View File

@ -44,6 +44,11 @@ security:
basic:
enabled: false
server:
session:
cookie:
http-only: true
# ===================================================================
# JHipster specific properties
# ===================================================================

View File

@ -181,7 +181,6 @@
<th class="text-right" data-translate="metrics.ehcache.hits">Hits</th>
<th class="text-right" data-translate="metrics.ehcache.misses">Misses</th>
<th class="text-right" data-translate="metrics.ehcache.evictioncount">Eviction count</th>
<th class="text-right" data-translate="metrics.ehcache.mean">Mean get time (ms)</th>
</tr>
</thead>
<tbody>
@ -191,7 +190,6 @@
<td class="text-right">{{vm.metrics.gauges[k + '.hits'].value}}</td>
<td class="text-right">{{vm.metrics.gauges[k + '.misses'].value}}</td>
<td class="text-right">{{vm.metrics.gauges[k + '.eviction-count'].value}}</td>
<td class="text-right">{{vm.metrics.gauges[k + '.mean-get-time'].value | number:2}}</td>
</tr>
</tbody>
</table>

View File

@ -8,11 +8,6 @@
httpConfig.$inject = ['$urlRouterProvider', '$httpProvider', 'httpRequestInterceptorCacheBusterProvider', '$urlMatcherFactoryProvider'];
function httpConfig($urlRouterProvider, $httpProvider, httpRequestInterceptorCacheBusterProvider, $urlMatcherFactoryProvider) {
//enable CSRF
$httpProvider.defaults.xsrfCookieName = 'CSRF-TOKEN';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRF-TOKEN';
//Cache everything except rest api requests
httpRequestInterceptorCacheBusterProvider.setMatchlist([/.*api.*/, /.*protected.*/], true);

View File

@ -6,9 +6,9 @@
.factory('authExpiredInterceptor', authExpiredInterceptor);
authExpiredInterceptor.$inject = ['$rootScope', '$q', '$injector', '$document'];
authExpiredInterceptor.$inject = ['$rootScope', '$q', '$injector'];
function authExpiredInterceptor($rootScope, $q, $injector, $document) {
function authExpiredInterceptor($rootScope, $q, $injector) {
var service = {
responseError: responseError
};
@ -28,40 +28,8 @@
}
var LoginService = $injector.get('LoginService');
LoginService.open();
} else if (response.status === 403 && response.config.method !== 'GET' && getCSRF() === '') {
// If the CSRF token expired, then try to get a new CSRF token and retry the old request
var $http = $injector.get('$http');
return $http.get('/').finally(function() { return afterCSRFRenewed(response); });
}
return $q.reject(response);
}
function getCSRF() {
var doc = $document[0];
if (doc) {
var name = 'CSRF-TOKEN=';
var ca = doc.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) === ' ') {c = c.substring(1);}
if (c.indexOf(name) !== -1) {
return c.substring(name.length, c.length);
}
}
}
return '';
}
function afterCSRFRenewed(oldResponse) {
if (getCSRF() !== '') {
// retry the old request after the new CSRF-TOKEN is obtained
var $http = $injector.get('$http');
return $http(oldResponse.config);
} else {
// unlikely get here but reject with the old response any way and avoid infinite loop
return $q.reject(oldResponse);
}
}
}
})();

View File

@ -1,110 +0,0 @@
/*!
* angular-loading-bar v0.9.0
* https://chieffancypants.github.io/angular-loading-bar
* Copyright (c) 2016 Wes Cruver
* License: MIT
*/
/* Make clicks pass-through */
#loading-bar,
#loading-bar-spinner {
pointer-events: none;
-webkit-pointer-events: none;
-webkit-transition: 350ms linear all;
-moz-transition: 350ms linear all;
-o-transition: 350ms linear all;
transition: 350ms linear all;
}
#loading-bar.ng-enter,
#loading-bar.ng-leave.ng-leave-active,
#loading-bar-spinner.ng-enter,
#loading-bar-spinner.ng-leave.ng-leave-active {
opacity: 0;
}
#loading-bar.ng-enter.ng-enter-active,
#loading-bar.ng-leave,
#loading-bar-spinner.ng-enter.ng-enter-active,
#loading-bar-spinner.ng-leave {
opacity: 1;
}
#loading-bar .bar {
-webkit-transition: width 350ms;
-moz-transition: width 350ms;
-o-transition: width 350ms;
transition: width 350ms;
background: #29d;
position: fixed;
z-index: 10002;
top: 0;
left: 0;
width: 100%;
height: 2px;
border-bottom-right-radius: 1px;
border-top-right-radius: 1px;
}
/* Fancy blur effect */
#loading-bar .peg {
position: absolute;
width: 70px;
right: 0;
top: 0;
height: 2px;
opacity: .45;
-moz-box-shadow: #29d 1px 0 6px 1px;
-ms-box-shadow: #29d 1px 0 6px 1px;
-webkit-box-shadow: #29d 1px 0 6px 1px;
box-shadow: #29d 1px 0 6px 1px;
-moz-border-radius: 100%;
-webkit-border-radius: 100%;
border-radius: 100%;
}
#loading-bar-spinner {
display: block;
position: fixed;
z-index: 10002;
top: 10px;
left: 10px;
}
#loading-bar-spinner .spinner-icon {
width: 14px;
height: 14px;
border: solid 2px transparent;
border-top-color: #29d;
border-left-color: #29d;
border-radius: 50%;
-webkit-animation: loading-bar-spinner 400ms linear infinite;
-moz-animation: loading-bar-spinner 400ms linear infinite;
-ms-animation: loading-bar-spinner 400ms linear infinite;
-o-animation: loading-bar-spinner 400ms linear infinite;
animation: loading-bar-spinner 400ms linear infinite;
}
@-webkit-keyframes loading-bar-spinner {
0% { -webkit-transform: rotate(0deg); transform: rotate(0deg); }
100% { -webkit-transform: rotate(360deg); transform: rotate(360deg); }
}
@-moz-keyframes loading-bar-spinner {
0% { -moz-transform: rotate(0deg); transform: rotate(0deg); }
100% { -moz-transform: rotate(360deg); transform: rotate(360deg); }
}
@-o-keyframes loading-bar-spinner {
0% { -o-transform: rotate(0deg); transform: rotate(0deg); }
100% { -o-transform: rotate(360deg); transform: rotate(360deg); }
}
@-ms-keyframes loading-bar-spinner {
0% { -ms-transform: rotate(0deg); transform: rotate(0deg); }
100% { -ms-transform: rotate(360deg); transform: rotate(360deg); }
}
@keyframes loading-bar-spinner {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}

View File

@ -1,341 +0,0 @@
/*!
* angular-loading-bar v0.9.0
* https://chieffancypants.github.io/angular-loading-bar
* Copyright (c) 2016 Wes Cruver
* License: MIT
*/
/*
* angular-loading-bar
*
* intercepts XHR requests and creates a loading bar.
* Based on the excellent nprogress work by rstacruz (more info in readme)
*
* (c) 2013 Wes Cruver
* License: MIT
*/
(function() {
'use strict';
// Alias the loading bar for various backwards compatibilities since the project has matured:
angular.module('angular-loading-bar', ['cfp.loadingBarInterceptor']);
angular.module('chieffancypants.loadingBar', ['cfp.loadingBarInterceptor']);
/**
* loadingBarInterceptor service
*
* Registers itself as an Angular interceptor and listens for XHR requests.
*/
angular.module('cfp.loadingBarInterceptor', ['cfp.loadingBar'])
.config(['$httpProvider', function ($httpProvider) {
var interceptor = ['$q', '$cacheFactory', '$timeout', '$rootScope', '$log', 'cfpLoadingBar', function ($q, $cacheFactory, $timeout, $rootScope, $log, cfpLoadingBar) {
/**
* The total number of requests made
*/
var reqsTotal = 0;
/**
* The number of requests completed (either successfully or not)
*/
var reqsCompleted = 0;
/**
* The amount of time spent fetching before showing the loading bar
*/
var latencyThreshold = cfpLoadingBar.latencyThreshold;
/**
* $timeout handle for latencyThreshold
*/
var startTimeout;
/**
* calls cfpLoadingBar.complete() which removes the
* loading bar from the DOM.
*/
function setComplete() {
$timeout.cancel(startTimeout);
cfpLoadingBar.complete();
reqsCompleted = 0;
reqsTotal = 0;
}
/**
* Determine if the response has already been cached
* @param {Object} config the config option from the request
* @return {Boolean} retrns true if cached, otherwise false
*/
function isCached(config) {
var cache;
var defaultCache = $cacheFactory.get('$http');
var defaults = $httpProvider.defaults;
// Choose the proper cache source. Borrowed from angular: $http service
if ((config.cache || defaults.cache) && config.cache !== false &&
(config.method === 'GET' || config.method === 'JSONP')) {
cache = angular.isObject(config.cache) ? config.cache
: angular.isObject(defaults.cache) ? defaults.cache
: defaultCache;
}
var cached = cache !== undefined ?
cache.get(config.url) !== undefined : false;
if (config.cached !== undefined && cached !== config.cached) {
return config.cached;
}
config.cached = cached;
return cached;
}
return {
'request': function(config) {
// Check to make sure this request hasn't already been cached and that
// the requester didn't explicitly ask us to ignore this request:
if (!config.ignoreLoadingBar && !isCached(config)) {
$rootScope.$broadcast('cfpLoadingBar:loading', {url: config.url});
if (reqsTotal === 0) {
startTimeout = $timeout(function() {
cfpLoadingBar.start();
}, latencyThreshold);
}
reqsTotal++;
cfpLoadingBar.set(reqsCompleted / reqsTotal);
}
return config;
},
'response': function(response) {
if (!response || !response.config) {
$log.error('Broken interceptor detected: Config object not supplied in response:\n https://github.com/chieffancypants/angular-loading-bar/pull/50');
return response;
}
if (!response.config.ignoreLoadingBar && !isCached(response.config)) {
reqsCompleted++;
$rootScope.$broadcast('cfpLoadingBar:loaded', {url: response.config.url, result: response});
if (reqsCompleted >= reqsTotal) {
setComplete();
} else {
cfpLoadingBar.set(reqsCompleted / reqsTotal);
}
}
return response;
},
'responseError': function(rejection) {
if (!rejection || !rejection.config) {
$log.error('Broken interceptor detected: Config object not supplied in rejection:\n https://github.com/chieffancypants/angular-loading-bar/pull/50');
return $q.reject(rejection);
}
if (!rejection.config.ignoreLoadingBar && !isCached(rejection.config)) {
reqsCompleted++;
$rootScope.$broadcast('cfpLoadingBar:loaded', {url: rejection.config.url, result: rejection});
if (reqsCompleted >= reqsTotal) {
setComplete();
} else {
cfpLoadingBar.set(reqsCompleted / reqsTotal);
}
}
return $q.reject(rejection);
}
};
}];
$httpProvider.interceptors.push(interceptor);
}]);
/**
* Loading Bar
*
* This service handles adding and removing the actual element in the DOM.
* Generally, best practices for DOM manipulation is to take place in a
* directive, but because the element itself is injected in the DOM only upon
* XHR requests, and it's likely needed on every view, the best option is to
* use a service.
*/
angular.module('cfp.loadingBar', [])
.provider('cfpLoadingBar', function() {
this.autoIncrement = true;
this.includeSpinner = true;
this.includeBar = true;
this.latencyThreshold = 100;
this.startSize = 0.02;
this.parentSelector = 'body';
this.spinnerTemplate = '<div id="loading-bar-spinner"><div class="spinner-icon"></div></div>';
this.loadingBarTemplate = '<div id="loading-bar"><div class="bar"><div class="peg"></div></div></div>';
this.$get = ['$injector', '$document', '$timeout', '$rootScope', function ($injector, $document, $timeout, $rootScope) {
var $animate;
var $parentSelector = this.parentSelector,
loadingBarContainer = angular.element(this.loadingBarTemplate),
loadingBar = loadingBarContainer.find('div').eq(0),
spinner = angular.element(this.spinnerTemplate);
var incTimeout,
completeTimeout,
started = false,
status = 0;
var autoIncrement = this.autoIncrement;
var includeSpinner = this.includeSpinner;
var includeBar = this.includeBar;
var startSize = this.startSize;
/**
* Inserts the loading bar element into the dom, and sets it to 2%
*/
function _start() {
if (!$animate) {
$animate = $injector.get('$animate');
}
$timeout.cancel(completeTimeout);
// do not continually broadcast the started event:
if (started) {
return;
}
var document = $document[0];
var parent = document.querySelector ?
document.querySelector($parentSelector)
: $document.find($parentSelector)[0]
;
if (! parent) {
parent = document.getElementsByTagName('body')[0];
}
var $parent = angular.element(parent);
var $after = parent.lastChild && angular.element(parent.lastChild);
$rootScope.$broadcast('cfpLoadingBar:started');
started = true;
if (includeBar) {
$animate.enter(loadingBarContainer, $parent, $after);
}
if (includeSpinner) {
$animate.enter(spinner, $parent, loadingBarContainer);
}
_set(startSize);
}
/**
* Set the loading bar's width to a certain percent.
*
* @param n any value between 0 and 1
*/
function _set(n) {
if (!started) {
return;
}
var pct = (n * 100) + '%';
loadingBar.css('width', pct);
status = n;
// increment loadingbar to give the illusion that there is always
// progress but make sure to cancel the previous timeouts so we don't
// have multiple incs running at the same time.
if (autoIncrement) {
$timeout.cancel(incTimeout);
incTimeout = $timeout(function() {
_inc();
}, 250);
}
}
/**
* Increments the loading bar by a random amount
* but slows down as it progresses
*/
function _inc() {
if (_status() >= 1) {
return;
}
var rnd = 0;
// TODO: do this mathmatically instead of through conditions
var stat = _status();
if (stat >= 0 && stat < 0.25) {
// Start out between 3 - 6% increments
rnd = (Math.random() * (5 - 3 + 1) + 3) / 100;
} else if (stat >= 0.25 && stat < 0.65) {
// increment between 0 - 3%
rnd = (Math.random() * 3) / 100;
} else if (stat >= 0.65 && stat < 0.9) {
// increment between 0 - 2%
rnd = (Math.random() * 2) / 100;
} else if (stat >= 0.9 && stat < 0.99) {
// finally, increment it .5 %
rnd = 0.005;
} else {
// after 99%, don't increment:
rnd = 0;
}
var pct = _status() + rnd;
_set(pct);
}
function _status() {
return status;
}
function _completeAnimation() {
status = 0;
started = false;
}
function _complete() {
if (!$animate) {
$animate = $injector.get('$animate');
}
$rootScope.$broadcast('cfpLoadingBar:completed');
_set(1);
$timeout.cancel(completeTimeout);
// Attempt to aggregate any start/complete calls within 500ms:
completeTimeout = $timeout(function() {
var promise = $animate.leave(loadingBarContainer, _completeAnimation);
if (promise && promise.then) {
promise.then(_completeAnimation);
}
$animate.leave(spinner);
}, 500);
}
return {
start : _start,
set : _set,
status : _status,
inc : _inc,
complete : _complete,
autoIncrement : this.autoIncrement,
includeSpinner : this.includeSpinner,
latencyThreshold : this.latencyThreshold,
parentSelector : this.parentSelector,
startSize : this.startSize
};
}]; //
}); // wtf javascript. srsly
})(); //

View File

@ -1 +0,0 @@
#loading-bar,#loading-bar-spinner{pointer-events:none;-webkit-pointer-events:none;-webkit-transition:350ms linear all;-moz-transition:350ms linear all;-o-transition:350ms linear all;transition:350ms linear all}#loading-bar-spinner.ng-enter,#loading-bar-spinner.ng-leave.ng-leave-active,#loading-bar.ng-enter,#loading-bar.ng-leave.ng-leave-active{opacity:0}#loading-bar-spinner.ng-enter.ng-enter-active,#loading-bar-spinner.ng-leave,#loading-bar.ng-enter.ng-enter-active,#loading-bar.ng-leave{opacity:1}#loading-bar .bar{-webkit-transition:width 350ms;-moz-transition:width 350ms;-o-transition:width 350ms;transition:width 350ms;background:#29d;position:fixed;z-index:10002;top:0;left:0;width:100%;height:2px;border-bottom-right-radius:1px;border-top-right-radius:1px}#loading-bar .peg{position:absolute;width:70px;right:0;top:0;height:2px;opacity:.45;-moz-box-shadow:#29d 1px 0 6px 1px;-ms-box-shadow:#29d 1px 0 6px 1px;-webkit-box-shadow:#29d 1px 0 6px 1px;box-shadow:#29d 1px 0 6px 1px;-moz-border-radius:100%;-webkit-border-radius:100%;border-radius:100%}#loading-bar-spinner{display:block;position:fixed;z-index:10002;top:10px;left:10px}#loading-bar-spinner .spinner-icon{width:14px;height:14px;border:2px solid transparent;border-top-color:#29d;border-left-color:#29d;border-radius:50%;-webkit-animation:loading-bar-spinner 400ms linear infinite;-moz-animation:loading-bar-spinner 400ms linear infinite;-ms-animation:loading-bar-spinner 400ms linear infinite;-o-animation:loading-bar-spinner 400ms linear infinite;animation:loading-bar-spinner 400ms linear infinite}@-webkit-keyframes loading-bar-spinner{0%{-webkit-transform:rotate(0);transform:rotate(0)}100%{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}@-moz-keyframes loading-bar-spinner{0%{-moz-transform:rotate(0);transform:rotate(0)}100%{-moz-transform:rotate(360deg);transform:rotate(360deg)}}@-o-keyframes loading-bar-spinner{0%{-o-transform:rotate(0);transform:rotate(0)}100%{-o-transform:rotate(360deg);transform:rotate(360deg)}}@-ms-keyframes loading-bar-spinner{0%{-ms-transform:rotate(0);transform:rotate(0)}100%{-ms-transform:rotate(360deg);transform:rotate(360deg)}}@keyframes loading-bar-spinner{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}

View File

@ -1,7 +0,0 @@
/*!
* angular-loading-bar v0.9.0
* https://chieffancypants.github.io/angular-loading-bar
* Copyright (c) 2016 Wes Cruver
* License: MIT
*/
!function(){"use strict";angular.module("angular-loading-bar",["cfp.loadingBarInterceptor"]),angular.module("chieffancypants.loadingBar",["cfp.loadingBarInterceptor"]),angular.module("cfp.loadingBarInterceptor",["cfp.loadingBar"]).config(["$httpProvider",function(a){var b=["$q","$cacheFactory","$timeout","$rootScope","$log","cfpLoadingBar",function(b,c,d,e,f,g){function h(){d.cancel(j),g.complete(),l=0,k=0}function i(b){var d,e=c.get("$http"),f=a.defaults;!b.cache&&!f.cache||b.cache===!1||"GET"!==b.method&&"JSONP"!==b.method||(d=angular.isObject(b.cache)?b.cache:angular.isObject(f.cache)?f.cache:e);var g=void 0!==d?void 0!==d.get(b.url):!1;return void 0!==b.cached&&g!==b.cached?b.cached:(b.cached=g,g)}var j,k=0,l=0,m=g.latencyThreshold;return{request:function(a){return a.ignoreLoadingBar||i(a)||(e.$broadcast("cfpLoadingBar:loading",{url:a.url}),0===k&&(j=d(function(){g.start()},m)),k++,g.set(l/k)),a},response:function(a){return a&&a.config?(a.config.ignoreLoadingBar||i(a.config)||(l++,e.$broadcast("cfpLoadingBar:loaded",{url:a.config.url,result:a}),l>=k?h():g.set(l/k)),a):(f.error("Broken interceptor detected: Config object not supplied in response:\n https://github.com/chieffancypants/angular-loading-bar/pull/50"),a)},responseError:function(a){return a&&a.config?(a.config.ignoreLoadingBar||i(a.config)||(l++,e.$broadcast("cfpLoadingBar:loaded",{url:a.config.url,result:a}),l>=k?h():g.set(l/k)),b.reject(a)):(f.error("Broken interceptor detected: Config object not supplied in rejection:\n https://github.com/chieffancypants/angular-loading-bar/pull/50"),b.reject(a))}}}];a.interceptors.push(b)}]),angular.module("cfp.loadingBar",[]).provider("cfpLoadingBar",function(){this.autoIncrement=!0,this.includeSpinner=!0,this.includeBar=!0,this.latencyThreshold=100,this.startSize=.02,this.parentSelector="body",this.spinnerTemplate='<div id="loading-bar-spinner"><div class="spinner-icon"></div></div>',this.loadingBarTemplate='<div id="loading-bar"><div class="bar"><div class="peg"></div></div></div>',this.$get=["$injector","$document","$timeout","$rootScope",function(a,b,c,d){function e(){if(k||(k=a.get("$animate")),c.cancel(m),!r){var e=b[0],g=e.querySelector?e.querySelector(n):b.find(n)[0];g||(g=e.getElementsByTagName("body")[0]);var h=angular.element(g),i=g.lastChild&&angular.element(g.lastChild);d.$broadcast("cfpLoadingBar:started"),r=!0,v&&k.enter(o,h,i),u&&k.enter(q,h,o),f(w)}}function f(a){if(r){var b=100*a+"%";p.css("width",b),s=a,t&&(c.cancel(l),l=c(function(){g()},250))}}function g(){if(!(h()>=1)){var a=0,b=h();a=b>=0&&.25>b?(3*Math.random()+3)/100:b>=.25&&.65>b?3*Math.random()/100:b>=.65&&.9>b?2*Math.random()/100:b>=.9&&.99>b?.005:0;var c=h()+a;f(c)}}function h(){return s}function i(){s=0,r=!1}function j(){k||(k=a.get("$animate")),d.$broadcast("cfpLoadingBar:completed"),f(1),c.cancel(m),m=c(function(){var a=k.leave(o,i);a&&a.then&&a.then(i),k.leave(q)},500)}var k,l,m,n=this.parentSelector,o=angular.element(this.loadingBarTemplate),p=o.find("div").eq(0),q=angular.element(this.spinnerTemplate),r=!1,s=0,t=this.autoIncrement,u=this.includeSpinner,v=this.includeBar,w=this.startSize;return{start:e,set:f,status:h,inc:g,complete:j,autoIncrement:this.autoIncrement,includeSpinner:this.includeSpinner,latencyThreshold:this.latencyThreshold,parentSelector:this.parentSelector,startSize:this.startSize}}]})}();

View File

@ -1,163 +0,0 @@
#!/usr/bin/env node
/**
* Copyright 2012-2014 Alex Sexton, Eemeli Aro, and Contributors
*
* Licensed under the MIT License
*/
var
nopt = require('nopt'),
fs = require('fs'),
Path = require('path'),
glob = require('glob'),
async = require('async'),
MessageFormat = require('../'),
knownOpts = {
"locale" : String,
"inputdir" : Path,
"output" : Path,
"watch" : Boolean,
"namespace" : String,
"include" : String,
"stdout" : Boolean,
"module" : Boolean,
"verbose" : Boolean,
"help" : Boolean
},
description = {
"locale" : "locale(s) to use [mandatory]",
"inputdir" : "directory containing messageformat files to compile",
"output" : "output where messageformat will be compiled",
"namespace" : "global object in the output containing the templates",
"include" : "glob patterns for files to include from `inputdir`",
"stdout" : "print the result in stdout instead of writing in a file",
"watch" : "watch `inputdir` for changes",
"module" : "create a commonJS module, instead of a global window variable",
"verbose" : "print logs for debug"
},
defaults = {
"inputdir" : process.cwd(),
"output" : process.cwd(),
"watch" : false,
"namespace" : 'i18n',
"include" : '**/*.json',
"stdout" : false,
"verbose" : false,
"module" : false,
"help" : false
},
shortHands = {
"l" : "--locale",
"i" : "--inputdir",
"o" : "--output",
"ns" : "--namespace",
"I" : "--include",
"m" : "--module",
"s" : "--stdout",
"w" : "--watch",
"v" : "--verbose",
"?" : "--help"
},
options = (function() {
var o = nopt(knownOpts, shortHands, process.argv, 2);
for (var key in defaults) {
o[key] = o[key] || defaults[key];
}
if (o.argv.remain) {
if (o.argv.remain.length >= 1) o.inputdir = o.argv.remain[0];
if (o.argv.remain.length >= 2) o.output = o.argv.remain[1];
}
if (!o.locale || o.help) {
var usage = ['Usage: messageformat -l [locale] [OPTIONS] [INPUT_DIR] [OUTPUT_DIR]'];
if (!o.help) {
usage.push("Try 'messageformat --help' for more information.");
console.error(usage.join('\n'));
process.exit(-1);
}
usage.push('\nAvailable options:');
for (var key in shortHands) {
var desc = description[shortHands[key].toString().substr(2)];
if (desc) usage.push(' -' + key + ',\t' + shortHands[key] + (shortHands[key].length < 8 ? ' ' : '') + '\t' + desc);
}
console.log(usage.join('\n'));
process.exit(0);
}
if (fs.existsSync(o.output) && fs.statSync(o.output).isDirectory()) {
o.output = Path.join(o.output, 'i18n.js');
}
o.namespace = o.module ? 'module.exports' : o.namespace.replace(/^window\./, '')
return o;
})(),
_log = (options.verbose ? function(s) { console.log(s); } : function(){});
function write(options, data) {
if (options.stdout) { _log(''); return console.log(data); }
fs.writeFile( options.output, data, 'utf8', function(err) {
if (err) return console.error('--->\t' + err.message);
_log(options.output + " written.");
});
}
function parseFileSync(dir, file) {
var path = Path.join(dir, file),
file_parts = file.split(/[.\/]+/),
r = { namespace: null, locale: null, data: null };
if (!fs.statSync(path).isFile()) {
_log('Skipping ' + file);
return null;
}
r.namespace = file.replace(/\.[^.]*$/, '').replace(/\\/g, '/');
for (var i = file_parts.length - 1; i >= 0; --i) {
if (file_parts[i] in MessageFormat.plurals) { r.locale = file_parts[i]; break; }
}
try {
_log('Building ' + JSON.stringify(r.namespace) + ' from `' + file + '` with ' + (r.locale ? 'locale ' + JSON.stringify(r.locale) : 'default locale'));
r.data = JSON.parse(fs.readFileSync(path, 'utf8'));
} catch (ex) {
console.error('--->\tRead error in ' + path + ': ' + ex.message);
}
return r;
}
function build(options, callback) {
var lc = options.locale.trim().split(/[ ,]+/),
mf = new MessageFormat(lc[0]),
messages = {},
compileOpt = { global: options.namespace, locale: {} };
lc.slice(1).forEach(function(l){
var pf = mf.runtime.pluralFuncs[l] = MessageFormat.plurals[l];
if (!pf) throw 'Plural function for locale `' + l + '` not found';
});
_log('Input dir: ' + options.inputdir);
_log('Included locales: ' + lc.join(', '));
glob(options.include, {cwd: options.inputdir}, function(err, files) {
if (!err) async.each(files,
function(file, cb) {
var r = parseFileSync(options.inputdir, file);
if (r && r.data) {
messages[r.namespace] = r.data;
if (r.locale) compileOpt.locale[r.namespace] = r.locale;
}
cb();
},
function() {
var fn_str = mf.compile(messages, compileOpt).toString();
fn_str = fn_str.replace(/^\s*function\b[^{]*{\s*/, '').replace(/\s*}\s*$/, '');
var data = options.module ? fn_str : '(function(G) {\n' + fn_str + '\n})(this);';
return callback(options, data.trim() + '\n');
}
);
});
}
build(options, write);
if (options.watch) {
_log('watching for changes in ' + options.inputdir + '...\n');
require('watchr').watch({
path: options.inputdir,
ignorePaths: [ options.output ],
listener: function(changeType, filePath) { if (/\.json$/.test(filePath)) build(options, write); }
});
}

View File

@ -1,176 +0,0 @@
#!/usr/bin/env node
'use strict';
var fs = require('fs');
var _ = require('lodash');
var path = require('path');
var mkdirp = require('mkdirp');
var Modernizr = require(path.resolve(__dirname + '/../lib/cli.js'));
var yargs = require('yargs')
.options('h', {
alias: 'help',
describe: 'Print Help'
})
.options('V', {
alias: ['v', 'version'],
describe: 'Print the version and exit'
})
.options('f', {
alias: 'features',
describe: 'comma separated list of feature detects'
})
.options('o', {
alias: 'options',
describe: 'comma separated list of extensibility options'
})
.options('c', {
alias: 'config',
describe: 'Path to a JSON file containing Modernizr configuration. See lib/config-all.json for an example'
})
.options('d', {
alias: 'dest',
describe: 'Path to write the Modernizr build file to. Defaults to ./modernizr.js'
})
.options('m', {
alias: 'metadata',
describe: 'Path to where the Modernizr feature-detect metadata should be saved. Defaults to ./metadata.json'
})
.options('u', {
alias: 'uglify',
describe: 'uglify/minify the output'
})
.options('q', {
alias: 'quiet',
describe: 'Silence all output'
});
var argv = yargs.argv;
var cwd = process.cwd();
var dest = cwd + '/modernizr.js';
var inlineConfig;
var configPath;
var config;
function log() {
if (!argv.q) {
console.log.apply(console, arguments);
}
}
function stringify(obj, minified) {
var replacer = function(key, value) {
return value;
};
var args = minified ? [replacer,2] : [];
args.unshift(obj);
return JSON.stringify.apply(JSON, args);
}
if (argv.h) {
yargs.showHelp();
process.exit();
}
if (argv.V) {
var pkg = require('../package.json');
console.log('Modernizr v' + pkg.version);
process.exit();
}
if (argv.d) {
dest = path.normalize(argv.d);
var exists = fs.existsSync(dest);
var isDir = exists && fs.statSync(dest).isDirectory();
var fileRequested = _.endsWith(dest, '.js');
if ((exists && isDir) || (!exists && !fileRequested)) {
dest = path.join(dest, 'modernizr.js');
}
mkdirp.sync(path.dirname(dest));
}
if (argv.m) {
// path.normalize is used instead of normalize in order to support ~
// we get an absolute path on the fallback from cwd, and any user supplied
// argument will be relative to their current directory.
var metaDest = path.normalize(argv.m === true ? cwd + '/metadata.json' : argv.m);
Modernizr.metadata(function(metadata) {
mkdirp.sync(path.dirname(metaDest));
fs.writeFileSync(metaDest, stringify(metadata, !argv.u));
log('metadata saved to ' + metaDest);
});
if (!argv.d) {
// return early unless we explictly request Modernizr to be built
return;
}
}
if (argv.o || argv.f) {
var metadata = Modernizr.metadata();
var options = Modernizr.options();
var find = function(config, source) {
if (!config) {
return;
}
return config
.replace(/-/g, ',')
.split(',')
.map(function(prop) {
var obj = _.find(source, {property: prop});
if (_.isUndefined(obj)) {
throw new Error('invalid key value name - ' + prop);
} else {
return obj.amdPath || obj.property;
}
});
};
config = {
'feature-detects': find(argv.f, metadata),
'options': find(argv.o, options)
};
inlineConfig = true;
}
if (argv.c) {
try {
configPath = fs.realpathSync(argv.c);
} catch (e) {
console.error(argv.c + ' does not exist.');
process.exit(1);
}
if (!configPath) {
configPath = path.resolve(__dirname, '../lib/config-all.json');
}
}
try {
if (!config && !configPath) {
console.error('config file, inline features, or options required.');
yargs.showHelp();
process.exit(1)
} else {
config = config || {};
if (configPath) {
config = _.extend(config, require(configPath));
}
}
} catch (e) {
console.error(configPath + ' is not valid JSON.');
console.error(e);
process.exit(1);
}
if (argv.u) {
config.minify = true;
}
Modernizr.build(config, function(output) {
fs.writeFileSync(dest, output);
log('Modernizr build saved to ' + dest);
});

View File

@ -1,153 +0,0 @@
var root = require('find-parent-dir').sync(__dirname, 'package.json');
var build = require(root + 'lib/build');
var expect = require('expect.js');
describe('cli/build', function() {
it('should build without error', function() {
expect(function() {build();}).to.not.throwError();
});
describe('custom builds', function(done) {
it('should build without errors when using a custom build', function() {
expect(function() {
build({'feature-detects': ['css/boxsizing']}, done);
}).to.not.throwError();
});
it('should include the requested options', function(done) {
build({'feature-detects': ['css/boxsizing']}, function(file) {
expect(file).to.contain('boxsizing');
done();
});
});
it('should exclude options that are not requested', function(done) {
build({'feature-detects': ['dom/classlist']}, function(file) {
expect(file).to.contain('classlist');
expect(file).to.not.contain('boxsizing');
done();
});
});
it('should strip out DOC comments when `uglify`ing', function(done) {
var config = {
minify: true,
'feature-detects': ['css/boxsizing']
};
build(config, function(file) {
expect(file).to.not.contain('Box Sizing');
done();
});
});
it('should inject the proper classPath when configured', function(done) {
var prefix = 'TEST_PREFIX';
var config = {
classPrefix: prefix,
setClasses: true
};
var configRE = /_config:\s*?({[^}]*})/m;
build(config, function(file) {
var parsedConfig = file.match(configRE);
parsedConfig = JSON.parse(parsedConfig[1].replace(/'/g, '"'));
expect(parsedConfig.classPrefix).to.be(prefix);
done();
});
});
it('should inject the proper classPath when configured and minified', function(done) {
var prefix = 'TEST_PREFIX';
var config = {
classPrefix: prefix,
setClasses: true,
minify: true
};
var configRE = /_config:\s*?({[^}]*})/m;
build(config, function(file) {
var parsedConfig = file.match(configRE);
//use eval becuase the minified code creates non valid JSON.
parsedConfig = eval('(' + parsedConfig[1].replace(/'/g, '"') + ')');
expect(parsedConfig.classPrefix).to.be(prefix);
done();
});
});
describe('unminified', function() {
var output;
before(function(done) {
var config = {
'feature-detects': ['css/boxsizing']
};
build(config, function(file) {
output = file;
done();
});
});
it('strips out the modernizr-init/build `define` section', function() {
var defineRe = /define\("modernizr-(init|build)"\)/m;
expect(defineRe.test(output)).to.be(false);
});
it('strips out the `define` section', function() {
var docRe = /define\(.*?\{/;
expect(docRe.test(output)).to.be(false);
});
it('strips out the `require` section', function() {
var requireRe = /require[^\{\r\n]+\{/;
expect(requireRe.test(output)).to.be(false);
});
it('replaces __VERSION__ ', function() {
expect(output).to.not.contain('__VERSION__');
});
});
describe('minified', function() {
var output;
before(function(done) {
var config = {
'feature-detects': ['css/boxsizing'],
minify: true
};
build(config, function(file) {
output = file;
done();
});
});
it('strips out the modernizr-init/build `define` section', function() {
var defineRe = /define\("modernizr-(init|build)"\)/m;
expect(defineRe.test(output)).to.be(false);
});
it('strips out the `define` section', function() {
var docRe = /define\(.*?\{/;
expect(docRe.test(output)).to.be(false);
});
it('strips out the `require` section', function() {
var requireRe = /require[^\{\r\n]+\{/;
expect(requireRe.test(output)).to.be(false);
});
it('replaces __VERSION__ ', function() {
expect(output).to.not.contain('__VERSION__');
});
});
});
});

View File

@ -1,21 +0,0 @@
var root = require('find-parent-dir').sync(__dirname, 'package.json');
var expect = require('expect.js');
var cp = require('child_process');
var Modernizr = require(root + 'lib/cli');
describe('cli', function() {
it('exposes a build function', function() {
expect(Modernizr.build).to.be.a('function');
});
it('exposes a metadata function', function() {
expect(Modernizr.metadata).to.be.a('function');
});
it('does not throw when being executed', function(done) {
cp.exec('node ' + root + '/bin/modernizr -f adownload', done);
});
});

View File

@ -1,212 +0,0 @@
var root = require('find-parent-dir').sync(__dirname, 'package.json');
var proxyquire = require('proxyquire').noPreserveCache();
var metadata = require(root + 'lib/metadata');
var expect = require('expect.js');
var Joi = require('joi');
describe('cli/metadata', function() {
it('should ignore .DS_STORE files', function(done) {
var metadata = proxyquire(root + 'lib/metadata', {
'file': {
'walkSync': function(dir, cb) {
cb('/', [], ['.DS_Store']);
}
}
});
metadata(function(data) {
expect(data).to.be.an('array');
expect(data).to.have.length(0);
done();
});
});
it('should throw on malformed metadata', function() {
var metadata = proxyquire(root + 'lib/metadata', {
'fs': {
'readFileSync': function() {
return '/*! { !*/';
}
}
});
expect(metadata).to.throwException(/Error Parsing Metadata/);
});
it('should not throw when metadata is missing', function() {
var metadata = proxyquire(root + 'lib/metadata', {
'fs': {
'readFileSync': function() {
return 'sup dude';
}
}
});
expect(metadata).to.not.throwException(/Error Parsing Metadata/);
});
it('should throw on malformed deps', function() {
var metadata = proxyquire(root + 'lib/metadata', {
'fs': {
'readFileSync': function() {
return 'define([[],';
}
}
});
expect(metadata).to.throwException(/Couldn't parse dependencies/);
});
it('should throw if we can\'t find the define', function() {
var metadata = proxyquire(root + 'lib/metadata', {
'fs': {
'readFileSync': function() {
return 'defin([]),';
}
}
});
expect(metadata).to.throwException(/Couldn't find the define/);
});
it('should use amdPath as a fallback for name', function() {
var metadata = proxyquire(root + 'lib/metadata', {
'file': {
'walkSync': function(dir, cb) {
cb('/', [], ['fakeDetect.js']);
}
},
'fs': {
'readFileSync': function() {
return '/*! { "property": "fake"}!*/ define([],';
}
}
});
var result = metadata();
expect(result.name).to.equal(result.amdPath);
});
it('should throw if we can\'t find the define', function() {
var metadata = proxyquire(root + 'lib/metadata', {
'fs': {
'readFileSync': function() {
return '/*! { "polyfills": ["fake"]}!*/ define([],';
}
}
});
expect(metadata).to.throwException(/Polyfill not found/);
});
it('should throw if we can\'t find the define', function() {
var metadata = proxyquire(root + 'lib/metadata', {
'fs': {
'readFileSync': function() {
return '/*! { "property": "fake", "cssclass": "realFake"}!*/ define([],';
}
}
});
var firstResult = metadata()[0];
expect(firstResult.cssclass).to.be(null);
});
it('should rename `docs` to `doc` when found', function() {
var metadata = proxyquire(root + 'lib/metadata', {
'fs': {
'readFileSync': function() {
return '/*! { "docs": "originally docs" }!*/ define([],';
}
}
});
var firstResult = metadata()[0];
expect(firstResult.docs).to.be(undefined);
expect(firstResult.doc).to.match(/originally docs/);
});
it('returns a json blob when invoked without callback', function() {
expect(metadata()).to.be.an('array');
});
it('return nothing when given a callback', function() {
expect(metadata(function noop() {})).to.be(undefined);
});
it('pass the json blob when given a callback', function(done) {
metadata(function(data) {
expect(data).to.be.an('array');
done();
});
});
describe('returns an array of valid objects', function() {
var schema = Joi.object().keys({
amdPath: Joi.string().required(),
name: Joi.string().required(),
path: Joi.string().required(),
doc: Joi.alternatives().try(Joi.string(), null),
caniuse: Joi.alternatives().try(Joi.string(), null),
async: Joi.boolean(),
aliases: Joi.array().items(Joi.string()),
builderAliases: Joi.array().items(Joi.string()),
knownBugs: Joi.array().items(Joi.string()),
warnings: Joi.array().items(Joi.string()),
authors: Joi.array().items(Joi.string()),
tags: Joi.array().items(Joi.string()),
deps: Joi.array().items(Joi.string()),
notes: Joi.array().items(
Joi.object().keys({
name: Joi.string().required(),
href: Joi.string().required()
})
).unique(),
cssclass: Joi.alternatives().try(
Joi.string().lowercase(),
Joi.array().items(Joi.string().lowercase())
).required(),
property: Joi.alternatives().try(
Joi.string().lowercase(),
Joi.array().items(Joi.string().lowercase())
).required(),
polyfills: Joi.array().items(
Joi.object().keys({
name: Joi.string().required(),
authors: Joi.array().items(Joi.string()),
notes: Joi.array().items(Joi.string()),
href: Joi.string().required(),
licenses: Joi.array().items(Joi.string()).required()
})
).unique()
});
metadata(function(data) {
data.forEach(function(obj) {
var err = schema.validate(obj).error;
it('for ' + obj.name, function() {
expect(err).to.be(null);
});
});
});
});
});

View File

@ -1,34 +0,0 @@
var root = require('find-parent-dir').sync(__dirname, 'package.json');
var options = require(root + 'lib/options');
var expect = require('expect.js');
var Joi = require('joi');
var schema = Joi.array().items(
Joi.object().keys({
name: Joi.string(),
property: Joi.string()
})
);
describe('cli/options', function() {
this.timeout(20000);
it('should return an array of objects in a callback', function(done) {
options(function(opts) {
var err = schema.validate(opts).error;
expect(err).to.be(null);
done(err);
});
});
it('should return the array of objects immediately after the first run', function() {
var err = schema.validate(options()).error;
expect(err).to.be(null);
});
it('should return all jsdoc info when the second arg is true', function() {
expect(options(null, true) !== options(null)).to.be(true);
expect(options(null, true)[0].description).to.not.be(undefined);
});
});

View File

@ -13,7 +13,7 @@
"dependencies": {
"angular": ">=1.2.0"
},
"homepage": "https://github.com/sroze/ngInfiniteScroll",
"homepage": "https://github.com/ng-infinite-scroll/ng-infinite-scroll-bower",
"version": "1.3.0",
"_release": "1.3.0",
"_resolution": {
@ -21,7 +21,7 @@
"tag": "1.3.0",
"commit": "d44e8e3f3207da5ee15e0027d253f617b9334ac8"
},
"_source": "https://github.com/sroze/ngInfiniteScroll.git",
"_source": "https://github.com/ng-infinite-scroll/ng-infinite-scroll-bower.git",
"_target": "1.3.0",
"_originalSource": "ngInfiniteScroll"
}

View File

@ -1,189 +0,0 @@
/* ng-infinite-scroll - v1.3.0 - 2016-06-30 */
angular.module('infinite-scroll', []).value('THROTTLE_MILLISECONDS', null).directive('infiniteScroll', [
'$rootScope', '$window', '$interval', 'THROTTLE_MILLISECONDS', function($rootScope, $window, $interval, THROTTLE_MILLISECONDS) {
return {
scope: {
infiniteScroll: '&',
infiniteScrollContainer: '=',
infiniteScrollDistance: '=',
infiniteScrollDisabled: '=',
infiniteScrollUseDocumentBottom: '=',
infiniteScrollListenForEvent: '@'
},
link: function(scope, elem, attrs) {
var changeContainer, checkInterval, checkWhenEnabled, container, handleInfiniteScrollContainer, handleInfiniteScrollDisabled, handleInfiniteScrollDistance, handleInfiniteScrollUseDocumentBottom, handler, height, immediateCheck, offsetTop, pageYOffset, scrollDistance, scrollEnabled, throttle, unregisterEventListener, useDocumentBottom, windowElement;
windowElement = angular.element($window);
scrollDistance = null;
scrollEnabled = null;
checkWhenEnabled = null;
container = null;
immediateCheck = true;
useDocumentBottom = false;
unregisterEventListener = null;
checkInterval = false;
height = function(elem) {
elem = elem[0] || elem;
if (isNaN(elem.offsetHeight)) {
return elem.document.documentElement.clientHeight;
} else {
return elem.offsetHeight;
}
};
offsetTop = function(elem) {
if (!elem[0].getBoundingClientRect || elem.css('none')) {
return;
}
return elem[0].getBoundingClientRect().top + pageYOffset(elem);
};
pageYOffset = function(elem) {
elem = elem[0] || elem;
if (isNaN(window.pageYOffset)) {
return elem.document.documentElement.scrollTop;
} else {
return elem.ownerDocument.defaultView.pageYOffset;
}
};
handler = function() {
var containerBottom, containerTopOffset, elementBottom, remaining, shouldScroll;
if (container === windowElement) {
containerBottom = height(container) + pageYOffset(container[0].document.documentElement);
elementBottom = offsetTop(elem) + height(elem);
} else {
containerBottom = height(container);
containerTopOffset = 0;
if (offsetTop(container) !== void 0) {
containerTopOffset = offsetTop(container);
}
elementBottom = offsetTop(elem) - containerTopOffset + height(elem);
}
if (useDocumentBottom) {
elementBottom = height((elem[0].ownerDocument || elem[0].document).documentElement);
}
remaining = elementBottom - containerBottom;
shouldScroll = remaining <= height(container) * scrollDistance + 1;
if (shouldScroll) {
checkWhenEnabled = true;
if (scrollEnabled) {
if (scope.$$phase || $rootScope.$$phase) {
return scope.infiniteScroll();
} else {
return scope.$apply(scope.infiniteScroll);
}
}
} else {
if (checkInterval) {
$interval.cancel(checkInterval);
}
return checkWhenEnabled = false;
}
};
throttle = function(func, wait) {
var later, previous, timeout;
timeout = null;
previous = 0;
later = function() {
previous = new Date().getTime();
$interval.cancel(timeout);
timeout = null;
return func.call();
};
return function() {
var now, remaining;
now = new Date().getTime();
remaining = wait - (now - previous);
if (remaining <= 0) {
$interval.cancel(timeout);
timeout = null;
previous = now;
return func.call();
} else {
if (!timeout) {
return timeout = $interval(later, remaining, 1);
}
}
};
};
if (THROTTLE_MILLISECONDS != null) {
handler = throttle(handler, THROTTLE_MILLISECONDS);
}
scope.$on('$destroy', function() {
container.unbind('scroll', handler);
if (unregisterEventListener != null) {
unregisterEventListener();
unregisterEventListener = null;
}
if (checkInterval) {
return $interval.cancel(checkInterval);
}
});
handleInfiniteScrollDistance = function(v) {
return scrollDistance = parseFloat(v) || 0;
};
scope.$watch('infiniteScrollDistance', handleInfiniteScrollDistance);
handleInfiniteScrollDistance(scope.infiniteScrollDistance);
handleInfiniteScrollDisabled = function(v) {
scrollEnabled = !v;
if (scrollEnabled && checkWhenEnabled) {
checkWhenEnabled = false;
return handler();
}
};
scope.$watch('infiniteScrollDisabled', handleInfiniteScrollDisabled);
handleInfiniteScrollDisabled(scope.infiniteScrollDisabled);
handleInfiniteScrollUseDocumentBottom = function(v) {
return useDocumentBottom = v;
};
scope.$watch('infiniteScrollUseDocumentBottom', handleInfiniteScrollUseDocumentBottom);
handleInfiniteScrollUseDocumentBottom(scope.infiniteScrollUseDocumentBottom);
changeContainer = function(newContainer) {
if (container != null) {
container.unbind('scroll', handler);
}
container = newContainer;
if (newContainer != null) {
return container.bind('scroll', handler);
}
};
changeContainer(windowElement);
if (scope.infiniteScrollListenForEvent) {
unregisterEventListener = $rootScope.$on(scope.infiniteScrollListenForEvent, handler);
}
handleInfiniteScrollContainer = function(newContainer) {
if ((newContainer == null) || newContainer.length === 0) {
return;
}
if (newContainer.nodeType && newContainer.nodeType === 1) {
newContainer = angular.element(newContainer);
} else if (typeof newContainer.append === 'function') {
newContainer = angular.element(newContainer[newContainer.length - 1]);
} else if (typeof newContainer === 'string') {
newContainer = angular.element(document.querySelector(newContainer));
}
if (newContainer != null) {
return changeContainer(newContainer);
} else {
throw new Error("invalid infinite-scroll-container attribute.");
}
};
scope.$watch('infiniteScrollContainer', handleInfiniteScrollContainer);
handleInfiniteScrollContainer(scope.infiniteScrollContainer || []);
if (attrs.infiniteScrollParent != null) {
changeContainer(angular.element(elem.parent()));
}
if (attrs.infiniteScrollImmediateCheck != null) {
immediateCheck = scope.$eval(attrs.infiniteScrollImmediateCheck);
}
return checkInterval = $interval((function() {
if (immediateCheck) {
handler();
}
return $interval.cancel(checkInterval);
}));
}
};
}
]);
if (typeof module !== "undefined" && typeof exports !== "undefined" && module.exports === exports) {
module.exports = 'infinite-scroll';
}

View File

@ -1,2 +0,0 @@
/* ng-infinite-scroll - v1.3.0 - 2016-06-30 */
angular.module("infinite-scroll",[]).value("THROTTLE_MILLISECONDS",null).directive("infiniteScroll",["$rootScope","$window","$interval","THROTTLE_MILLISECONDS",function(a,b,c,d){return{scope:{infiniteScroll:"&",infiniteScrollContainer:"=",infiniteScrollDistance:"=",infiniteScrollDisabled:"=",infiniteScrollUseDocumentBottom:"=",infiniteScrollListenForEvent:"@"},link:function(e,f,g){var h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z;return z=angular.element(b),u=null,v=null,j=null,k=null,r=!0,y=!1,x=null,i=!1,q=function(a){return a=a[0]||a,isNaN(a.offsetHeight)?a.document.documentElement.clientHeight:a.offsetHeight},s=function(a){if(a[0].getBoundingClientRect&&!a.css("none"))return a[0].getBoundingClientRect().top+t(a)},t=function(a){return a=a[0]||a,isNaN(window.pageYOffset)?a.document.documentElement.scrollTop:a.ownerDocument.defaultView.pageYOffset},p=function(){var b,d,g,h,l;return k===z?(b=q(k)+t(k[0].document.documentElement),g=s(f)+q(f)):(b=q(k),d=0,void 0!==s(k)&&(d=s(k)),g=s(f)-d+q(f)),y&&(g=q((f[0].ownerDocument||f[0].document).documentElement)),h=g-b,l=h<=q(k)*u+1,l?(j=!0,v?e.$$phase||a.$$phase?e.infiniteScroll():e.$apply(e.infiniteScroll):void 0):(i&&c.cancel(i),j=!1)},w=function(a,b){var d,e,f;return f=null,e=0,d=function(){return e=(new Date).getTime(),c.cancel(f),f=null,a.call()},function(){var g,h;return g=(new Date).getTime(),h=b-(g-e),h<=0?(c.cancel(f),f=null,e=g,a.call()):f?void 0:f=c(d,h,1)}},null!=d&&(p=w(p,d)),e.$on("$destroy",function(){if(k.unbind("scroll",p),null!=x&&(x(),x=null),i)return c.cancel(i)}),n=function(a){return u=parseFloat(a)||0},e.$watch("infiniteScrollDistance",n),n(e.infiniteScrollDistance),m=function(a){if(v=!a,v&&j)return j=!1,p()},e.$watch("infiniteScrollDisabled",m),m(e.infiniteScrollDisabled),o=function(a){return y=a},e.$watch("infiniteScrollUseDocumentBottom",o),o(e.infiniteScrollUseDocumentBottom),h=function(a){if(null!=k&&k.unbind("scroll",p),k=a,null!=a)return k.bind("scroll",p)},h(z),e.infiniteScrollListenForEvent&&(x=a.$on(e.infiniteScrollListenForEvent,p)),l=function(a){if(null!=a&&0!==a.length){if(a.nodeType&&1===a.nodeType?a=angular.element(a):"function"==typeof a.append?a=angular.element(a[a.length-1]):"string"==typeof a&&(a=angular.element(document.querySelector(a))),null!=a)return h(a);throw new Error("invalid infinite-scroll-container attribute.")}},e.$watch("infiniteScrollContainer",l),l(e.infiniteScrollContainer||[]),null!=g.infiniteScrollParent&&h(angular.element(f.parent())),null!=g.infiniteScrollImmediateCheck&&(r=e.$eval(g.infiniteScrollImmediateCheck)),i=c(function(){return r&&p(),c.cancel(i)})}}}]),"undefined"!=typeof module&&"undefined"!=typeof exports&&module.exports===exports&&(module.exports="infinite-scroll");

View File

@ -75,8 +75,7 @@
"objects": "Objects",
"hits": "Hits",
"misses": "Misses",
"evictioncount": "Eviction count",
"mean": "Mean get time (ms)"
"evictioncount": "Eviction count"
},
"datasource": {
"usage": "Usage",

View File

@ -84,7 +84,7 @@
function addApiKeyAuthorization(){
var apiKeyAuth = new SwaggerClient.ApiKeyAuthorization("X-CSRF-TOKEN", getCSRF(), "header");
var apiKeyAuth = new SwaggerClient.ApiKeyAuthorization("X-XSRF-TOKEN", getCSRF(), "header");
window.swaggerUi.api.clientAuthorizations.add("key", apiKeyAuth);
@ -93,7 +93,7 @@
}
function getCSRF() {
var name = "CSRF-TOKEN=";
var name = "XSRF-TOKEN=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];

View File

@ -34,7 +34,7 @@ class BankAccountGatlingTest extends Simulation {
val headers_http_authenticated = Map(
"Accept" -> """application/json""",
"X-CSRF-TOKEN" -> "${csrf_token}"
"X-XSRF-TOKEN" -> "${xsrf_token}"
)
val scn = scenario("Test the BankAccount entity")
@ -42,7 +42,7 @@ class BankAccountGatlingTest extends Simulation {
.get("/api/account")
.headers(headers_http)
.check(status.is(401))
.check(headerRegex("Set-Cookie", "CSRF-TOKEN=(.*);[\\s]?[P,p]ath=/").saveAs("csrf_token"))).exitHereIfFailed
.check(headerRegex("Set-Cookie", "XSRF-TOKEN=(.*);[\\s]").saveAs("xsrf_token"))).exitHereIfFailed
.pause(10)
.exec(http("Authentication")
.post("/api/authentication")
@ -50,13 +50,13 @@ class BankAccountGatlingTest extends Simulation {
.formParam("j_username", "admin")
.formParam("j_password", "admin")
.formParam("remember-me", "true")
.formParam("submit", "Login")).exitHereIfFailed
.formParam("submit", "Login")
.check(headerRegex("Set-Cookie", "XSRF-TOKEN=(.*);[\\s]").saveAs("xsrf_token"))).exitHereIfFailed
.pause(1)
.exec(http("Authenticated request")
.get("/api/account")
.headers(headers_http_authenticated)
.check(status.is(200))
.check(headerRegex("Set-Cookie", "CSRF-TOKEN=(.*);[\\s]?[P,p]ath=/").saveAs("csrf_token")))
.check(status.is(200)))
.pause(10)
.repeat(2) {
exec(http("Get all bankAccounts")

View File

@ -34,7 +34,7 @@ class LabelGatlingTest extends Simulation {
val headers_http_authenticated = Map(
"Accept" -> """application/json""",
"X-CSRF-TOKEN" -> "${csrf_token}"
"X-XSRF-TOKEN" -> "${xsrf_token}"
)
val scn = scenario("Test the Label entity")
@ -42,7 +42,7 @@ class LabelGatlingTest extends Simulation {
.get("/api/account")
.headers(headers_http)
.check(status.is(401))
.check(headerRegex("Set-Cookie", "CSRF-TOKEN=(.*);[\\s]?[P,p]ath=/").saveAs("csrf_token"))).exitHereIfFailed
.check(headerRegex("Set-Cookie", "XSRF-TOKEN=(.*);[\\s]").saveAs("xsrf_token"))).exitHereIfFailed
.pause(10)
.exec(http("Authentication")
.post("/api/authentication")
@ -50,13 +50,13 @@ class LabelGatlingTest extends Simulation {
.formParam("j_username", "admin")
.formParam("j_password", "admin")
.formParam("remember-me", "true")
.formParam("submit", "Login")).exitHereIfFailed
.formParam("submit", "Login")
.check(headerRegex("Set-Cookie", "XSRF-TOKEN=(.*);[\\s]").saveAs("xsrf_token"))).exitHereIfFailed
.pause(1)
.exec(http("Authenticated request")
.get("/api/account")
.headers(headers_http_authenticated)
.check(status.is(200))
.check(headerRegex("Set-Cookie", "CSRF-TOKEN=(.*);[\\s]?[P,p]ath=/").saveAs("csrf_token")))
.check(status.is(200)))
.pause(10)
.repeat(2) {
exec(http("Get all labels")

View File

@ -34,7 +34,7 @@ class OperationGatlingTest extends Simulation {
val headers_http_authenticated = Map(
"Accept" -> """application/json""",
"X-CSRF-TOKEN" -> "${csrf_token}"
"X-XSRF-TOKEN" -> "${xsrf_token}"
)
val scn = scenario("Test the Operation entity")
@ -42,7 +42,7 @@ class OperationGatlingTest extends Simulation {
.get("/api/account")
.headers(headers_http)
.check(status.is(401))
.check(headerRegex("Set-Cookie", "CSRF-TOKEN=(.*);[\\s]?[P,p]ath=/").saveAs("csrf_token"))).exitHereIfFailed
.check(headerRegex("Set-Cookie", "XSRF-TOKEN=(.*);[\\s]").saveAs("xsrf_token"))).exitHereIfFailed
.pause(10)
.exec(http("Authentication")
.post("/api/authentication")
@ -50,13 +50,13 @@ class OperationGatlingTest extends Simulation {
.formParam("j_username", "admin")
.formParam("j_password", "admin")
.formParam("remember-me", "true")
.formParam("submit", "Login")).exitHereIfFailed
.formParam("submit", "Login")
.check(headerRegex("Set-Cookie", "XSRF-TOKEN=(.*);[\\s]").saveAs("xsrf_token"))).exitHereIfFailed
.pause(1)
.exec(http("Authenticated request")
.get("/api/account")
.headers(headers_http_authenticated)
.check(status.is(200))
.check(headerRegex("Set-Cookie", "CSRF-TOKEN=(.*);[\\s]?[P,p]ath=/").saveAs("csrf_token")))
.check(status.is(200)))
.pause(10)
.repeat(2) {
exec(http("Get all operations")