java.io.FileNotFoundException: class path resource [/data/nroot/client_key.p12] cannot be opened because it does not exist - spring-amqp

I have updated the Spring-rabbit version from 1.7 to 2.2.8 to support SSL connection. the below exception is throwing when i mentioned external paths to key store & trust store i.e., outside the jar file.
2:40:53,853 |-ERROR in com.axon.log.dropwizard.AxonAMQPAppender[rabbitmq] - Failed to create customized Rabbit ConnectionFactory. org.springframework.amqp.AmqpIOException: java.io.FileNotFoundException: class path resource [/data/nroot/client_key.p12] cannot be opened because it does not exist
at org.springframework.amqp.AmqpIOException: java.io.FileNotFoundException: class path resource [/data/nroot/client_key.p12] cannot be opened because it does not exist
at at org.springframework.amqp.rabbit.support.RabbitExceptionTranslator.convertRabbitAccessException(RabbitExceptionTranslator.java:70)
at at org.springframework.amqp.rabbit.connection.RabbitConnectionFactoryBean.setUpSSL(RabbitConnectionFactoryBean.java:743)
at at org.springframework.amqp.rabbit.connection.RabbitConnectionFactoryBean.createInstance(RabbitConnectionFactoryBean.java:706)
at at org.springframework.amqp.rabbit.connection.RabbitConnectionFactoryBean.createInstance(RabbitConnectionFactoryBean.java:80)
at at org.springframework.beans.factory.config.AbstractFactoryBean.afterPropertiesSet(AbstractFactoryBean.java:142)
at at org.springframework.amqp.rabbit.connection.RabbitConnectionFactoryBean.afterPropertiesSet(RabbitConnectionFactoryBean.java:691)
at at org.springframework.amqp.rabbit.logback.AmqpAppender.createRabbitConnectionFactory(AmqpAppender.java:710)
at at org.springframework.amqp.rabbit.logback.AmqpAppender.start(AmqpAppender.java:675)
at at com.axon.log.dropwizard.AmqpAppenderFactory.build(AmqpAppenderFactory.java:373)
at at io.dropwizard.logging.DefaultLoggingFactory.configure(DefaultLoggingFactory.java:143)
at at io.dropwizard.cli.ConfiguredCommand.run(ConfiguredCommand.java:83)
at at io.dropwizard.cli.Cli.run(Cli.java:78)
at at io.dropwizard.Application.run(Application.java:93)
at at com.infa.products.axon.bulkupload.BulkUploadApplication.main(BulkUploadApplication.java:62)
Caused by: java.io.FileNotFoundException: class path resource [/data/nroot/client_key.p12] cannot be opened because it does not exist
at at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:180)
at at org.springframework.amqp.rabbit.connection.RabbitConnectionFactoryBean.configureKeyManagers(RabbitConnectionFactoryBean.java:776)
at at org.springframework.amqp.rabbit.connection.RabbitConnectionFactoryBean.setUpSSL(RabbitConnectionFactoryBean.java:725)
at ... 12 common frames omitted
12:40:53,853 |-INFO in ch.qos.logback.classic.AsyncAppender[async-rabbitmq] - Attaching appender named [rabbitmq] to AsyncAppender.
12:40:53,853 |-INFO in ch.qos.logback.classic.AsyncAppender[async-rabbitmq] - Setting discardingThreshold to 51
i have updated only spring-rabbit to 2.2.8.RELEASE. i have tried to update dependencies to latest, but ran into couple of other issues. then i have updated only spring-rabbit version to support SSL connection.
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.12'
compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.25'
compile 'com.google.code.gson:gson:2.8.1'
compile group: 'io.dropwizard', name: 'dropwizard-logging', version: '1.1.0'
compile group: 'net.logstash.logback', name: 'logstash-logback-encoder', version: '4.11'
compile group: 'ch.qos.logback.contrib', name: 'logback-json-classic', version: '0.1.2'
compile group: 'ch.qos.logback.contrib', name: 'logback-jackson', version: '0.1.5'
compile group: 'org.springframework.amqp', name: 'spring-rabbit', version: '2.2.8.RELEASE'
compile group: 'javax.servlet', name: 'javax.servlet-api', version: '3.0.1'
compile group: 'io.jsonwebtoken', name: 'jjwt', version: '0.8.0'
compile group: 'org.bitbucket.b_c', name: 'jose4j', version: '0.5.5'
}
YML config entry:
- type: rabbitmq
host: localhost
port: 5671
username: guest
password: =AXON:CIPHER:AES:128=CrYVHt53/OWVCgAXXrrZ2ufouJwnIdKQzF9VQlSR7NaDE1XpEGPyCznCL57Gpx+RKhrIKR+ytURDzrPv7qw8Rw==
exchange: axon_log_java
routingKey: log_routing_key
appName: Unison
enabled: true
secure: true
tlsVersion: TLSv1.2
keyStorePassword: MySecretPassword
trustStorePassword: MySecretPassword
clientKeyPath: /data/nroot/client_key.p12
trustStorePath: /data/nroot/rabbitstore
keyStoreType: PKCS12
trustStoreType: JKS
verifyHostname: false
==========
Yml properties setting to AMQPAppender:
#JsonTypeName("rabbitmq")
public class AmqpAppenderFactory extends AbstractAppenderFactory {
........
..............
...........
#Override
public Appender build(LoggerContext context, String applicationName, LayoutFactory layoutFactory, LevelFilterFactory levelFilterFactory, AsyncAppenderFactory asyncAppenderFactory) {
JsonLayout layout = new JsonLayout();
layout.setJsonFormatter(new JacksonJsonFormatter());
layout.setAppendLineSeparator(true);
layout.setTimestampFormatTimezoneId("UTC");
layout.setIncludeContextName(includeContextName);
//LayoutWrappingEncoder<ILoggingEvent> layoutEncoder = new LayoutWrappingEncoder<>();
//layoutEncoder.setLayout(layout);
final AxonAMQPAppender amqpAppender= new AxonAMQPAppender();
amqpAppender.setName(appenderName);
amqpAppender.setContext(context);
amqpAppender.setLayout(layout);
amqpAppender.setDeclareExchange(isDeclareExchange());
amqpAppender.setVirtualHost(getVHost());
amqpAppender.setHost(getHost());
amqpAppender.setContentType("application/json");
amqpAppender.setDurable(isDurable());
amqpAppender.setGenerateId(isGenerateId());
amqpAppender.setExchangeType(getExchangeType());
amqpAppender.setMaxSenderRetries(getMaxRetry());
amqpAppender.setPassword(getPassword());
amqpAppender.setUsername(getUsername());
amqpAppender.setPort(getPort());
amqpAppender.setRoutingKeyPattern(getRoutingKey());
amqpAppender.setExchangeName(getExchange());
amqpAppender.setApplicationId(getAppName());
amqpAppender.addFilter(levelFilterFactory.build(threshold));
**amqpAppender.setUseSsl(isSecure());
amqpAppender.setSslAlgorithm(getTlsVersion());
amqpAppender.setKeyStore(getClientKeyPath());
amqpAppender.setKeyStorePassphrase(getKeyStorePassword());
amqpAppender.setKeyStoreType(getKeyStoreType());
amqpAppender.setTrustStore(getTrustStorePath());
amqpAppender.setTrustStorePassphrase(getTrustStorePassword());
amqpAppender.setTrustStoreType(getTrustStoreType());
amqpAppender.setVerifyHostname(isVerifyHostname());**
String command = System.getProperty("centralized.logging");
if(false == getEnabled() || "false".equals(command)){
NullAppender nullAppender = new NullAppender();
nullAppender.setContext(context);
return wrapAsync(nullAppender,asyncAppenderFactory);
}
**amqpAppender.start();**
return wrapAsync(amqpAppender,asyncAppenderFactory);
}
}
AMQPAppender class:
public class AxonAMQPAppender extends AmqpAppender {
public static String APP_ID = "";
public static String SOURCE = "";
#Override
public Message postProcessMessageBeforeSend(Message message, Event event)
{
String body = new String(message.getBody());
//some line of code
return message;
}
}

I have resolved my issue.
By default its look for classpath or if we specify classpath: i.e., ClasspathResourceLoader
for external file paths need to specify file: i.e., its usesFileUrlResourceLoader

Related

Pulumi - how to pull a docker image from a private registry?

I've declared a Kubernetes deployment which has two containers. One is built locally, another needs to be pulled from a private registry.
const appImage = new docker.Image("ledgerImage", {
imageName: 'us.gcr.io/qwil-build/ledger',
build: "../../",
});
const ledgerDeployment = new k8s.extensions.v1beta1.Deployment("ledger", {
spec: {
template: {
metadata: {
labels: {name: "ledger"},
name: "ledger",
},
spec: {
containers: [
{
name: "api",
image: appImage.imageName,
},
{
name: "ssl-proxy",
image: "us.gcr.io/qwil-build/monolith-ssl-proxy:latest",
}
],
}
}
}
});
When I run pulumi up it hangs - this is happening because of a complaint that You don't have the needed permissions to perform this operation, and you may have invalid credentials. I see this complain when I run kubectl describe <name of pod>. However, when I run docker pull us.gcr.io/qwil-build/monolith-ssl-proxy:latest it executes just fine. I've re-reun gcloud auth configure-docker and it hasn't helped.
I found https://github.com/pulumi/pulumi-cloud/issues/112 but it seems that docker.Image requires a build arg which suggests to me it's meant for local images, not remote images.
How can I pull an image from a private registry?
EDIT:
Turns out I have a local dockerfile for building the SSL proxy I need. I've declared a new Image with
const sslImage = new docker.Image("sslImage", {
imageName: 'us.gcr.io/qwil-build/ledger-ssl-proxy',
build: {
context: "../../",
dockerfile: "../../Dockerfile.proxy"
}
});
And updated the image reference in the Deployment correctly. However, I'm still getting authentication problems.
I have a solution which uses only code, which I use to retrieve images from a private repository on Gitlab:
config.ts
import { Config } from "#pulumi/pulumi";
//
// Gitlab specific config.
//
const gitlabConfig = new Config("gitlab");
export const gitlab = {
registry: "registry.gitlab.com",
user: gitlabConfig.require("user"),
email: gitlabConfig.require("email"),
password: gitlabConfig.requireSecret("password"),
}
import * as config from "./config";
import { Base64 } from 'js-base64';
import * as kubernetes from "#pulumi/kubernetes";
[...]
const provider = new kubernetes.Provider("do-k8s", { kubeconfig })
const imagePullSecret = new kubernetes.core.v1.Secret(
"gitlab-registry",
{
type: "kubernetes.io/dockerconfigjson",
stringData: {
".dockerconfigjson": pulumi
.all([config.gitlab.registry, config.gitlab.user, config.gitlab.password, config.gitlab.email])
.apply(([server, username, password, email]) => {
return JSON.stringify({
auths: {
[server]: {
auth: Base64.encode(username + ":" + password),
username: username,
email: email,
password: password
}
}
})
})
}
},
{
provider: provider
}
);
// Then use the imagePullSecret in your deployment like this
deployment = new k8s.apps.v1.Deployment(name, {
spec: {
selector: { matchLabels: labels },
template: {
metadata: { labels: labels },
spec: {
imagePullSecrets: [{ name: args.imagePullSecret.metadata.apply(m => m.name) }],
containers: [container]
},
},
},
});
Turns out running pulumi destroy --yes && pulumi up --skip-preview --yes is what I needed. I guess I was in some weird inconsistent state but this is fixed now.
D'oh! Looks like RemoteImage is the answer: https://www.pulumi.com/docs/reference/pkg/nodejs/pulumi/docker/#RemoteImage
EDIT:
I tried
const sslImage = new docker.RemoteImage("sslImage", {
name: 'us.gcr.io/qwil-build/monolith-ssl-proxy:latest',
})
And I'm still getting authentication errors so this isn't the answer I think.
You need to give your cluster the credentials to your Docker Registry, so that it can pull the images from it.
The manual process would be:
docker login registry.gitlab.com
cat ~/.docker/config.json | base64
Then create a registry_secret.yaml with the output from above
apiVersion: v1
kind: Secret
metadata:
name: regsec
data:
.dockerconfigjson: ewJImF1dGhzIjogewoJCSJyZWdpc3RyeS5naXfRsYWsi7fQoJfSwKCSJIdHRwSGVhZGVycyI6IHsKCQkdiVXNlci1BZ2VudCI6ICJEb2NrZXItQ2xpZW50LzEaLjxzLxjUgKH9yIjogInN3YXJtIgp9
type: kubernetes.io/dockerconfigjson
and then apply it to your cluster with
kubectl apply -f registry_secret.yaml && kubectl get secrets
You can wrap that into Pulumi, as it supports yaml files like
new k8s.yaml.ConfigGroup("docker-secret", {files: "registry_secret.yaml"});
This only works if you have your credentials encoded in .docker/config.json and should not work if you are using a credential store
The alternative would be to create the secret directly by providing your user credentials and extracting the token
kubectl create secret docker-registry regsec \
--docker-server=registry.gitlab.com --docker-username=... \
--docker-email=... --docker-password=... \
--dry-run -o yaml | grep .dockerconfigjson: | sed -e 's/.dockerconfigjson://' | sed -e 's/^[ \t]*//'
This token can now be stored as a pulumi secret with
pulumi config set docker_token --secret <your_token>
and be used like this
import {Secret} from "#pulumi/kubernetes/core/v1";
import {Config} from "#pulumi/pulumi";
/**
* Creates a docker registry secret to pull images from private registries
*/
export class DockerRegistry {
constructor(provider: any) {
const config = new Config();
const dockerToken = config.require("docker_token");
new Secret("docker-registry-secret", {
metadata: {
name: "docker-registry-secret"
},
data: {
".dockerconfigjson": dockerToken
},
type: "kubernetes.io/dockerconfigjson"
}, {provider});
}
}

Simulate authentication or login when using Behat + Symfony

Most part of my app requires that the User is logged in and some parts requires the User has specific role.
I have this feature file.
Background:
Given I am logged in as "saif"
And I am making transaction for "Jaime Sangcap"
#critical #javascript
Scenario: Transaction having a sales person for commission
Given there is "General English Level 1" which costs "499" on the product list
When I add the "General English Level 1"
And I assign "Emy Ventura" as the sales person
Then I should see "Emy Ventura" as the sales person
And here is my Context file.
<?php
namespace Akademia\Institution\Behat\Sales\Context;
use Akademia\Institution\Behat\Common\Context\CanAuthenticateWithKernel;
use Akademia\Institution\Sales\Domain\Model\Client;
use Akademia\Institution\Sales\Domain\Model\ClientRepository;
use Behat\Behat\Tester\Exception\PendingException;
use Behat\Behat\Context\SnippetAcceptingContext;
use Behat\Mink\Driver\BrowserKitDriver;
use Behat\Mink\Exception\UnsupportedDriverActionException;
use Behat\MinkExtension\Context\MinkContext;
use Behat\Symfony2Extension\Context\KernelAwareContext;
use Behat\Symfony2Extension\Context\KernelDictionary;
use Doctrine\Common\DataFixtures\Purger\ORMPurger;
use Symfony\Component\BrowserKit\Cookie;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
class SalesUiContext extends MinkContext implements SnippetAcceptingContext, KernelAwareContext
{
use KernelDictionary;
/** #var ClientRepository */
private $clientRepository;
private $clientName;
/**
* #BeforeScenario
*/
public function clearData()
{
$em = $this->getContainer()->get('doctrine.orm.sales_entity_manager');
$em->getConnection()->executeQuery('SET foreign_key_checks = 0;');
$purger = new ORMPurger($em);
$purger->purge();
}
/**
* #BeforeScenario
*/
public function loadFixtures()
{
shell_exec('bin/console hautelook_alice:doctrine:fixtures:load -n --env=test');
}
/**
* #Given I am making transaction for :name
*/
public function iAmMakingTransactionFor($name)
{
$this->clientName = $name;
$this->clientRepository = $this->getContainer()->get('akademia_institution.sales.client_repository');
$this->clientRepository->add(Client::withMinimumDetails($name, '056xxxxxxx', 'irrelevant source'));
$this->visit(sprintf('clients/?keyword=%s', $name));
$this->clickLink('register');
}
/**
* #Given there is :arg1 which costs :arg2 on the product list
*/
public function thereIsWhichCostsOnTheProductList($arg1, $arg2)
{
throw new PendingException();
}
/**
* #When I add the :arg1
*/
public function iAddThe($arg1)
{
throw new PendingException();
}
/**
* #When I assign :arg1 as the sales person
*/
public function iAssignAsTheSalesPerson($arg1)
{
throw new PendingException();
}
/**
* #Then I should see :arg1 as the sales person
*/
public function iShouldSeeAsTheSalesPerson($arg1)
{
throw new PendingException();
}
/**
* #Given I am logged in as :username
* #Given I am logged in
*/
public function iAmLoggedInAs($username = null)
{
$driver = $this->getSession('symfony_session')->getDriver();
if (! ($driver instanceof BrowserKitDriver)) {
throw new UnsupportedDriverActionException('This step is only supported by the BrowserKitDriver', $driver);
}
$client = $driver->getClient();
$client->getCookieJar()->set(new Cookie(session_name(), true));
$session = $client->getContainer()->get('session');
$firewall = $this->getContainer()->getParameter('fos_user.firewall_name');
$user = $this->getContainer()->get('elite.user_repository')->findByUser($username);
$token = new UsernamePasswordToken($user, null, $firewall, $user->getRoles());
$session->set('_security_'.$firewall, serialize($token));
$session->save();
$cookie = new Cookie($session->getName(), $session->getId());
$client->getCookieJar()->set($cookie);
}
}
behat.yml file
default:
gherkin:
filters:
tags: "~#wip&&~#disabled"
extensions:
Behat\Symfony2Extension:
kernel:
env: test
Behat\MinkExtension:
base_url: http://elitesolutions.app
javascript_session: selenium2_session
default_session: goutte_session
sessions:
goutte_session:
goutte: ~
symfony_session:
symfony2: ~
selenium2_session:
selenium2:
wd_host: http://192.168.100.0/wd/hub
capabilities:
browser: firefox
version: ANY
suites:
sales:
paths: [ "%paths.base%/features/Sales" ]
contexts: [ Akademia\Institution\Behat\Sales\Context\SalesDomainContext ]
sales_ui:
paths: ["%paths.base%/features/Sales"]
contexts: [ Akademia\Institution\Behat\Sales\Context\SalesUiContext ]
filters:
tags: "#critical"
The Given I am logged in as "saif" is passing
But Im having error on the next step
And I am making transaction for "Jaime Sangcap" saying:
Link with id|title|alt|text "register" not found. (Behat\Mink\Exception\ElementNotFoundException)
Which I think is because when trying to visit the url, its being redirected to the login page and not on the intended url (page).
bacause most of my scenarios requires you're logged in I dont like to authenticate them on the real login form on every scenario.
Is there a way to do that, like manually setting the Token?
I've tried following this post but couldn't get it to work
EDIT:
I think the problem is Im using two database, the symfony2 session is using the test environment which points to elite_solutions_test while the selenium2 is using dev environment which points to elite_solutions_dev
here is my behat.yml
extensions:
Behat\Symfony2Extension:
kernel:
env: test
Behat\MinkExtension:
base_url: http://elitesolutions.app
default_session: symfony
javascript_session: javascript
browser_name: phantomjs
sessions:
goutte:
goutte: ~
symfony:
symfony2: ~
javascript:
selenium2:
wd_host: http://10.0.2.2:4444/wd/hub
parameters.yml
# This file is auto-generated during the composer install
parameters:
database_host: 127.0.0.1
database_port: 3306
database_name: elite_solutions_dev
database_user: homestead
database_password: secret
mailer_transport: smtp
mailer_host: 127.0.0.1
mailer_user: null
mailer_password: null
secret: ThisTokenIsNotSoSecretChangeIt
config_test.yml
imports:
- { resource: config_dev.yml }
framework:
test: ~
session:
storage_id: session.storage.mock_file
profiler:
collect: false
web_profiler:
toolbar: false
intercept_redirects: false
swiftmailer:
disable_delivery: true
doctrine:
dbal:
driver: pdo_mysql
host: "%database_host%"
port: "%database_port%"
dbname: elite_solutions_test
user: "%database_user%"
password: "%database_password%"
charset: UTF8
#security:
# firewalls:
# main:
# http_basic: ~
hautelook_alice:
db_drivers:
orm: true
locale: en_US # Locale to used for faker; must be a valid Faker locale otherwise will fallback to en_EN
seed: 1 # A seed to make sure faker generates data consistently across runs, set to null to disable
persist_once: false # Only persist objects once if multiple files are passed
loading_limit: 5 # Maximum number of time the loader will try to load the files passed
How should I tell the selenium2 to use the test environment? or should I add app_test.php?

Grails 3 db migrations

Just upgraded from grails 2.3.11 to 3.2.0.M2
Have a problem with dbm-gorm-diff and other dbm-* scripts
My app has multiproject structure. Domain classes placed in separate plugin.
Build.gradle
buildscript {
repositories {
mavenLocal()
maven { url "https://repo.grails.org/grails/core" }
}
dependencies {
classpath "org.grails:grails-gradle-plugin:$grailsVersion"
classpath "org.grails.plugins:hibernate5:6.0.0.M2"
classpath "org.grails.plugins:database-migration:2.0.0.RC4"
}
}
version "0.1"
group "core"
apply plugin:"eclipse"
apply plugin:"idea"
apply plugin:"org.grails.grails-plugin"
apply plugin:"org.grails.grails-plugin-publish"
configurations.all {
resolutionStrategy.cacheChangingModulesFor 0, 'seconds'
}
repositories {
mavenLocal()
maven { url "https://repo.grails.org/grails/core" }
}
dependencyManagement {
imports {
mavenBom "org.grails:grails-bom:$grailsVersion"
}
applyMavenExclusions false
}
dependencies {
compile "org.springframework.boot:spring-boot-starter-logging"
compile "org.springframework.boot:spring-boot-autoconfigure"
compile "org.grails:grails-core"
compile "org.grails:grails-dependencies"
compile "org.grails.plugins:hibernate5"
compile "org.grails.plugins:cache"
compile "org.hibernate:hibernate-core:5.1.0.Final"
compile "org.hibernate:hibernate-ehcache:5.1.0.Final"
console "org.grails:grails-console"
profile "org.grails.profiles:plugin:3.2.0.M2"
provided "org.grails:grails-plugin-services"
provided "org.grails:grails-plugin-domain-class"
provided 'javax.servlet:javax.servlet-api:3.1.0'
runtime "org.grails.plugins:database-migration:2.0.0.RC4"
runtime "mysql:mysql-connector-java:5.1.39"
testCompile "org.grails:grails-plugin-testing"
}
grailsPublish {
// TODO: Provide values here
user = 'user'
key = 'key'
githubSlug = 'app/core'
license {
name = 'Apache-2.0'
}
title = "Core"
desc = "***"
developers = ["***"]
portalUser = ""
portalPassword = ""
}
sourceSets {
main {
resources {
srcDir "grails-app/migrations"
}
}
}
application.yml
grails:
profile: plugin
codegen:
defaultPackage: core
spring:
transactionManagement:
proxies: false
info:
app:
name: '#info.app.name#'
version: '#info.app.version#'
grailsVersion: '#info.app.grailsVersion#'
spring:
groovy:
template:
check-template-location: false
---
grails:
plugin:
databasemigration:
updateOnStart: true
updateOnStartFileNames:
- changelog.groovy
- changelog-part-2.groovy
hibernate:
cache:
queries: false
use_second_level_cache: true
use_query_cache: false
region.factory_class: 'org.hibernate.cache.ehcache.EhCacheRegionFactory'
dataSource:
dbCreate: none
driverClassName: "com.mysql.jdbc.Driver"
dialect: "org.hibernate.dialect.MySQL5InnoDBDialect"
url: "jdbc:mysql://localhost:3306/project?zeroDateTimeBehavior=convertToNull&autoreconnect=true&useUnicode=true&characterEncoding=UTF-8&characterSetResults=UTF-8"
username: "root"
password: "root"
properties:
jmxEnabled: true
initialSize: 5
maxActive: 50
minIdle: 5
maxIdle: 25
maxWait: 10000
maxAge: 600000
timeBetweenEvictionRunsMillis: 5000
minEvictableIdleTimeMillis: 60000
validationQuery: SELECT 1
validationQueryTimeout: 3
validationInterval: 15000
testOnBorrow: true
testWhileIdle: true
testOnReturn: false
jdbcInterceptors: ConnectionState
defaultTransactionIsolation: 2 # TRANSACTION_READ_COMMITTED
Stacktrace
2016-08-16 18:57:06.731 WARN 5736 --- [ main] o.s.mock.web.MockServletContext : Couldn't determine real path of resource class path resource [src/main/webapp/WEB-INF/sitemesh.xml]
java.io.FileNotFoundException: class path resource [src/main/webapp/WEB-INF/sitemesh.xml] cannot be resolved to URL because it does not exist
at org.springframework.core.io.ClassPathResource.getURL(ClassPathResource.java:187) ~[spring-core-4.3.1.RELEASE.jar:4.3.1.RELEASE]
at org.springframework.core.io.AbstractFileResolvingResource.getFile(AbstractFileResolvingResource.java:48) ~[spring-core-4.3.1.RELEASE.jar:4.3.1.RELEASE]
at org.springframework.mock.web.MockServletContext.getRealPath(MockServletContext.java:458) ~[spring-test-4.3.1.RELEASE.jar:4.3.1.RELEASE]
at org.grails.web.sitemesh.Grails5535Factory.<init>(Grails5535Factory.java:78) [grails-web-sitemesh-3.2.0.M2.jar:3.2.0.M2]
at org.grails.web.servlet.view.SitemeshLayoutViewResolver.loadSitemeshConfig(SitemeshLayoutViewResolver.java:105) [grails-web-gsp-3.2.0.M2.jar:3.2.0.M2]
at org.grails.web.servlet.view.SitemeshLayoutViewResolver.init(SitemeshLayoutViewResolver.java:67) [grails-web-gsp-3.2.0.M2.jar:3.2.0.M2]
at org.grails.web.servlet.view.SitemeshLayoutViewResolver.onApplicationEvent(SitemeshLayoutViewResolver.java:146) [grails-web-gsp-3.2.0.M2.jar:3.2.0.M2]
at org.grails.web.servlet.view.SitemeshLayoutViewResolver.onApplicationEvent(SitemeshLayoutViewResolver.java:42) [grails-web-gsp-3.2.0.M2.jar:3.2.0.M2]
at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:166) [spring-context-4.3.1.RELEASE.jar:4.3.1.RELEASE]
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:138) [spring-context-4.3.1.RELEASE.jar:4.3.1.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:382) [spring-context-4.3.1.RELEASE.jar:4.3.1.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:336) [spring-context-4.3.1.RELEASE.jar:4.3.1.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:877) [spring-context-4.3.1.RELEASE.jar:4.3.1.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:544) [spring-context-4.3.1.RELEASE.jar:4.3.1.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759) [spring-boot-1.4.0.RC1.jar:1.4.0.RC1]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:369) [spring-boot-1.4.0.RC1.jar:1.4.0.RC1]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:313) [spring-boot-1.4.0.RC1.jar:1.4.0.RC1]
at grails.boot.GrailsApp.run(GrailsApp.groovy:55) [grails-core-3.2.0.M2.jar:3.2.0.M2]
at grails.ui.command.GrailsApplicationContextCommandRunner.run(GrailsApplicationContextCommandRunner.groovy:55) [grails-console-3.2.0.M2.jar:3.2.0.M2]
at grails.ui.command.GrailsApplicationContextCommandRunner.main(GrailsApplicationContextCommandRunner.groovy:102) [grails-console-3.2.0.M2.jar:3.2.0.M2]
2016-08-16 18:57:07.035 INFO 5736 --- [ main] .c.GrailsApplicationContextCommandRunner : Started GrailsApplicationContextCommandRunner in 21.719 seconds (JVM running for 23.484)
2016-08-16 18:57:07.035 INFO 5736 --- [ main] grails.boot.GrailsApp : Application starting in environment: development
Command execution error: Bean named 'sessionFactory' must be of type [org.springframework.beans.factory.FactoryBean], but was actually of type [org.hibernate.internal.SessionFactoryImpl]
2016-08-16 18:57:07.185 INFO 5736 --- [ Thread-7] g.u.s.DevelopmentWebApplicationContext : Closing grails.ui.support.DevelopmentWebApplicationContext#2abc224d: startup date [Tue Aug 16 18:56:48 MSK 2016]; root of context hierarchy
2016-08-16 18:57:07.382 INFO 5736 --- [ Thread-7] o.s.c.support.DefaultLifecycleProcessor : Stopping beans in phase -2147483648
2016-08-16 18:57:07.406 INFO 5736 --- [ Thread-7] o.s.j.e.a.AnnotationMBeanExporter : Unregistering JMX-exposed beans on shutdown
Can you help me?
Already found it. This is known issue - https://github.com/grails-plugins/grails-database-migration/issues/81
Discussed here: Grails 3 schemaExport contains warning with FileNotFoundException that looks for sitemesh.xml
You can ignore it. Still a problem in Grails 4.

how to apply Jasypt plugin in grails 2.3.7

I am trying to apply Jasypt plugin in my application to encrypt fields of my table.
here's my code below.
DOMAIN CLASS
import com.bloomhealthco.jasypt.GormEncryptedStringType;
class TestForm {
String name
String age
String gender
static mapping = {
name type: GormEncryptedStringType
age type: GormEncryptedStringType
gender type: GormEncryptedStringType
}
static constraints = {
}
}
BUILDCONFIG
plugins {
// plugins for the build system only
build ":tomcat:7.0.52.1"
// plugins for the compile step
compile ":scaffolding:2.0.2"
compile ':cache:1.1.1'
compile ":jasypt-encryption:1.2.1"
// plugins needed at runtime but not for compilation
runtime ":hibernate:3.6.10.9" //or ":hibernate4:4.3.4"
}
CONFIG
//Database encryption configuration
Jasypt {
algorithm = "PBEWITHSHA256AND256BITAES-CBC-BC"
providerName = "BC"
password = "c3kr37"
keyObtentionIterations = 1000
}
all those i have done in my application, This also successfully downloads jasypt plugin. but when i try to save record it show the following error
Error 500: Internal Server Error
URI:
/grailsTest/testForm/save
Class:
org.jasypt.exceptions.EncryptionInitializationException
Message:
No string encryptor registered for hibernate with name "gormEncryptor"
Hope for the right direction to use this plugin, Thanks in advance.

Import external config value into main config in grails

I have an external config file ${userHome}/.grails/${appName}/config.groovy:
package configs
grails.conf.logDirectory = '/home/serek/tmp/mamlog'
which I would like to import into main grails Config.groovy
grails.config.locations = ["file:${userHome}/.grails/${appName}/config.groovy"]
print grails.conf.logDirectory
log4j = {
appenders {
rollingFile name: 'infoLog', file: "${grails.conf.logDirectory}/info.log", threshold: org.apache.log4j.Level.INFO, maxFileSize: "1024MB", append: true
rollingFile name: 'warnLog', file: 'warn.log', threshold: org.apache.log4j.Level.WARN, maxFileSize: "1024MB", append: true
console name: 'stdout', layout: pattern(conversionPattern: '%d{yyyyMMdd.HHmmss.SSS} %r [%t] %-5p %c %x - %m%n')
}
Unfortunately, print grails.conf.logDirectory is not visible in main config.
How can I handle that? Print outputs only [:]
Groovy: 2.1.9
Grails: 2.3.2
========================================
I found solution, ex Config.groovy:
import org.yaml.snakeyaml.Yaml
Yaml yaml = new Yaml()
def extConfFilePath = "${userHome}/.grails/${appName}/mam.yaml" //my external conf in yaml
def extConfFileContent = new File(extConfFilePath).text
def extConf = yaml.load(extConfFileContent)
grails.ext = extConf
rollingFile name: 'infoLog', file: extConf.logDirectory + "info.log", threshold: org.apache.log4j.Level.INFO, maxFileSize: "1024MB", append: true
I believe its because the external config files are pulled in after Config.groovy is executed. Therefore, println at that location doesn't work. Try printing it from any gsp page with,
println "logDir = ${grailsApplication.config.grails.conf.logDirectory}"

Resources