How do I modify the document root of the built-in tomcat instead of using the "src/main/webapp"
Set the path to your document root as server.tomcat.document-root in application.properties
#Value("${server.tomcat.document-root}")
private String documentRoot;
#Bean
public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer() {
return new WebServerFactoryCustomizer<ConfigurableWebServerFactory>() {
#Override
public void customize(ConfigurableWebServerFactory factory) {
if (factory instanceof TomcatServletWebServerFactory) {
TomcatServletWebServerFactory tomcat = (TomcatServletWebServerFactory) factory;
if (!StringUtils.isEmpty(documentRoot)) {
File root = new File(documentRoot);
tomcat.setDocumentRoot(root);
}
}
}
};
}
In your application.properties, add a property:
server.servlet.contextPath=/yourpathgoeshere
Related
I using zuul with many swagger resources (I have different links to specifics api-docs) so my question is how can I configure ng-swagger-gen config to generate all classes from many resources?
This is my ng-swagger-gen config:
{
"$schema": "./node_modules/ng-swagger-gen/ng-swagger-gen-schema.json",
"swagger": "http://localhost:8080/v2/api-docs",
"output": "src/api/",
"apiModule": true
}
And this is my swagger confing in zuul application
#Primary
#Configuration
public class SwaggerConfig implements SwaggerResourcesProvider {
#Override
public List<SwaggerResource> get() {
List<SwaggerResource> resources = new ArrayList<>();
resources.add(swaggerResource("USER-SERVICE", "/api/user/v2/api-docs"));
resources.add(swaggerResource("STORY-SERVICE", "/api/story/v2/api-docs"));
return resources;
}
private SwaggerResource swaggerResource(String name, String location) {
SwaggerResource swaggerResource = new SwaggerResource();
swaggerResource.setName(name);
swaggerResource.setLocation(location);
swaggerResource.setSwaggerVersion("2.0");
return swaggerResource;
}
}
While calling getTemplate() method it's throwing this error -
"Error resolving template [betreff_product_request], template might not exist or might not be accessible by any of the configured Template Resolvers".
Is it because of the wrong path I've mentioned in templateResolver.setPrefix("D:\\templates\\");?.
How can I solve this?
public class MailerTemplateEngine {
private final TemplateEngine templateEngine;
public MailerTemplateEngine() {
this.templateEngine = new org.thymeleaf.TemplateEngine();
FileTemplateResolver templateResolver = new FileTemplateResolver ();
templateResolver.setPrefix("D:\\templates\\");
templateResolver.setSuffix(".txt");
templateResolver.setTemplateMode(TemplateMode.TEXT);
templateResolver.setOrder(templateEngine.getTemplateResolvers().size());
templateResolver.setCharacterEncoding("UTF-8");
templateResolver.setCacheable(false);
templateResolver.setCheckExistence(true);
this.templateEngine.setTemplateResolver(templateResolver);
}
public String getTemplate(String templateName, HashMap<String,String> parameters) {
Context ctx = new Context();
if (parameters != null) {
parameters.forEach((k, v) -> {
ctx.setVariable(k, v);
});
}
return this.templateEngine.process(templateName, ctx).trim();
}
}
I was reading through the Spring Integration Documentation thinking that a file download would be pretty simple to implement. Instead, the article provided me with many different components that seem to over-qualify my needs:
The FTP Inbound Channel Adapter is a special listener that will connect to the FTP server and will listen for the remote directory events (e.g., new file created) at which point it will initiate a file transfer.
The streaming inbound channel adapter produces message with payloads of type InputStream, allowing files to be fetched without writing to the local file system.
Let's say I have a SessionFactory declared as follows:
#Bean
public SessionFactory<FTPFile> ftpSessionFactory() {
DefaultFtpSessionFactory sf = new DefaultFtpSessionFactory();
sf.setHost("localhost");
sf.setPort(20);
sf.setUsername("foo");
sf.setPassword("foo");
return new CachingSessionFactory<>(sf);
}
How do I go from here to downloading a single file on a given URL?
You can use an FtpRemoteFileTemplate...
#SpringBootApplication
public class So44194256Application implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(So44194256Application.class, args);
}
#Bean
public DefaultFtpSessionFactory ftpSessionFactory() {
DefaultFtpSessionFactory sf = new DefaultFtpSessionFactory();
sf.setHost("10.0.0.3");
sf.setUsername("ftptest");
sf.setPassword("ftptest");
return sf;
}
#Bean
public FtpRemoteFileTemplate template(DefaultFtpSessionFactory sf) {
return new FtpRemoteFileTemplate(sf);
}
#Autowired
private FtpRemoteFileTemplate template;
#Override
public void run(String... args) throws Exception {
template.get("foo/bar.txt",
inputStream -> FileCopyUtils.copy(inputStream,
new FileOutputStream(new File("/tmp/bar.txt"))));
}
}
To add to #garyrussell's answer:
In FTPS protocol, if you are behind a firewall, you will might encounter
Host attempting data connection x.x.x.x is not the same as server y.y.y.y error (as described here). The reason is the FtpSession instance returned from DefaultFtpsSessionFactory by default does remote verification test, i.e. it runs in an "active" mode.
The solution is to disable this verification on the FtpSession instance by setting the "passive mode", when you create the DefaultFtpsSessionFactory.
DefaultFtpsSessionFactory defaultFtpsSessionFactory() {
DefaultFtpsSessionFactory defaultFtpSessionFactory = new DefaultFtpsSessionFactory(){
#Override
public FtpSession getSession() {
FtpSession ftpSession = super.getSession();
ftpSession.getClientInstance().setRemoteVerificationEnabled(false);
return ftpSession;
}
};
defaultFtpSessionFactory.setHost("host");
defaultFtpSessionFactory.setPort(xx);
defaultFtpSessionFactory.setUsername("username");
defaultFtpSessionFactory.setPassword("password");
defaultFtpSessionFactory.setFileType(2); //binary data transfer
return defaultFtpSessionFactory;
}
following code block might be helpful
#Bean
public SessionFactory<LsEntry> sftpSessionFactory() {
DefaultSftpSessionFactory factory = new DefaultSftpSessionFactory(true) {
{
setHost("localhost");
setPort(20);
setUser("foo");
setPassword("foo");
setAllowUnknownKeys(true);
}
};
return new CachingSessionFactory<LsEntry>(factory);
}
#Bean
public SftpInboundFileSynchronizer sftpInboundFileSynchronizer() {
SftpInboundFileSynchronizer fileSynchronizer = new SftpInboundFileSynchronizer(sftpSessionFactory()) {
{
setDeleteRemoteFiles(true);
setRemoteDirectory("/remote");
setFilter(new SftpSimplePatternFileListFilter("*.txt"));
}
};
return fileSynchronizer;
}
#Bean
#InboundChannelAdapter(channel = "sftpChannel", poller = #Poller(fixedDelay = "600"))
public MessageSource<File> sftpMessageSource() {
SftpInboundFileSynchronizingMessageSource messageSource = new SftpInboundFileSynchronizingMessageSource(
sftpInboundFileSynchronizer()) {
{
setLocalDirectory(new File("/temp"));
setAutoCreateLocalDirectory(true);
setLocalFilter(new AcceptOnceFileListFilter<File>());
}
};
return messageSource;
}
obtained from https://github.com/edtoktay/spring-integraton
I've created the ConfigAdmin loaded some properties. After that I've saved them. My question is: how can I get the properties that I have stored?
I've created the ConfigAdmin in the Activator.java:
public class Activator implements BundleActivator {
private String configFile = "API.properties";
#Override
public void start(BundleContext bundleContext) throws Exception {
InputStream stream = (bundleContext.getBundle().getResource(configFile)).openStream();
Properties properties = new Properties();
properties.load(stream);
createConfigAdmin(properties);
}
#Override
public void stop(BundleContext bundleContext) throws Exception {
}
private boolean createConfigAdmin(Properties properties, BundleContext context) {
try {
Dictionary<String, String> props = new Hashtable<String, String>();
ServiceReference reference = context.getServiceReference(ConfigurationAdmin.class.getName());
ConfigurationAdmin admin = (ConfigurationAdmin) context.getService(reference);
Configuration configuration = admin.createFactoryConfiguration(pid.configAdminPID, null);
for(final String name: properties.stringPropertyNames())
props.put(name, properties.getProperty(name));
configuration.update(props);
return true;
} catch(Exception e)
{
e.printStackTrace();
return false;
}
}
}
Was your intention really to create a factory config? You only need it if you want to create several configs for the same factory pid.
If you simply want to create a simple configuration then just use admin.getConfiguration(oid) you can update the configuration in the same way you do now.
If you want to read the configuration afterwards you simply get it again. If you want to configure a bundle with this configuration you typically will create a ManagedService and publish it. See http://liquid-reality.de/display/liquid/2011/09/23/Karaf+Tutorial+Part+2+-+Using+the+Configuration+Admin+Service
I am doing an application in springs with maven. i wrote all properties in app.properties file
file structure is like this
src/main/resource
|_
| templates
| |_mytempaltefile.vm
|_ app.properties
i gave the path(absloute) in app.property
app.properties file
template.base.path=D\:/SVN/trunk/tfbdirect/src/main/resources/templates
utilities-spring.xml
<bean id="velocityEngine"
class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
<property name="velocityProperties">
<props>
<prop key="resource.loader">file</prop>
<prop key="file.resource.loader.class">
org.apache.velocity.runtime.resource.loader.FileResourceLoader
</prop>
<prop key="file.resource.loader.path">${template.base.path}</prop>
<prop key="file.resource.loader.cache">false</prop>
</props>
</property>
</bean>
my class
import java.util.HashMap;
import java.util.Map;
import org.apache.velocity.app.VelocityEngine;
import org.springframework.ui.velocity.VelocityEngineUtils;
import com.providerpay.tfbdirect.service.mail.MailSenderService;
public class LoginServiceImpl implements ILoginService{
/**
* Injected through Spring IOC
*/
ILoginDAO loginDAO;
ClaimRuleProcessServiceImpl claimRuleProcessServiceImpl;
PlatformTransactionManager txmanager;
//IForgotPasswordDAO forgotPasswordDAO;
private VelocityEngine velocityEngine;
private String appURL;
private MailSenderService mailSenderService;
TFBLogger log = TFBLoggerFactory.getLogger(RuleServer.class);
public String getAppURL() {
return appURL;
}
public void setAppURL(String appURL) {
this.appURL = appURL;
}
public MailSenderService getMailSenderService() {
return mailSenderService;
}
public VelocityEngine getVelocityEngine() {
return velocityEngine;
}
public void setVelocityEngine(VelocityEngine velocityEngine) {
this.velocityEngine = velocityEngine;
}
public void setMailSenderService(MailSenderService mailSenderService) {
this.mailSenderService = mailSenderService;
}
public ILoginDAO getLoginDAO() {
return loginDAO;
}
public void setLoginDAO(ILoginDAO loginDAO) {
this.loginDAO = loginDAO;
}
public ClaimRuleProcessServiceImpl getClaimRuleProcessServiceImpl() {
return claimRuleProcessServiceImpl;
}
public void setClaimRuleProcessServiceImpl(
ClaimRuleProcessServiceImpl claimRuleProcessServiceImpl) {
this.claimRuleProcessServiceImpl = claimRuleProcessServiceImpl;
}
public void setTxmanager(PlatformTransactionManager txmanager) {
this.txmanager = txmanager;
}
/**
* Validates Login
* #param loginView
* #return
*/
public boolean isValidLogin(LoginView loginView) {
/* create tx definition object */
DefaultTransactionDefinition paramTransactionDefinition = new DefaultTransactionDefinition();
TransactionStatus status = txmanager.getTransaction(paramTransactionDefinition );
boolean result = false;
try{
LoginEntity loginEntity = BeanMapper.INSTANCE.viewToEntityMapper(loginView);
Feedback feedback = claimRuleProcessServiceImpl.validateClaimEligibility(loginEntity);
log.info( "Rule executed was " +feedback.getAll());
for (FeedbackMessage feedbackmessaage :feedback.getAll())
{
log.info("\n--------------");
log.info(feedbackmessaage.getRuleCd());
log.info(feedbackmessaage.getMessage());
log.info(feedbackmessaage.getSeverity().getName());
log.info("\n--------------");
}
result = loginDAO.isValidLogin(loginEntity);
log.debug("result = {}", result);
txmanager.commit(status);
}catch(Exception e){
txmanager.rollback(status);
throw new TfbException("Error occured while validating login credentials");
}
return result;
}
#Autowired
VelocityEngine velocityengine;
public boolean mailResetLink(LoginView loginView) {
String toEmailAddress;
LoginEntity loginEntity = BeanMapper.INSTANCE.viewToEntityMapper(loginView);
/* getting user Email from DAO*/
toEmailAddress = loginDAO.getEmailByUsername(loginEntity);
if(toEmailAddress != null && toEmailAddress.trim().length() > 0)
{
Map<String, Object> model = new HashMap<String, Object>();
model.put("user", loginEntity);
model.put("appURL", appURL);
String body = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "emailTemplate.vm","UTF-8", model);
mailSenderService.sendMail("from mail", toEmailAddress, "Password Reset Link",body);
}
else
{
return false;
}
return true;
}
public boolean resetPassword(LoginView loginView)
{
LoginEntity loginEntity = BeanMapper.INSTANCE.viewToEntityMapper(loginView);
return loginDAO.resetPassword(loginEntity);
}
}
every thing fine but i need to change the absolute path to relative path.. i tried many ways.
i tried like following
template.base.path=/templates/
but still getting below error .
ResourceManager : unable to find resource 'emailTemplate.vm' in any resource loader.
can any one help me..
Thanks in advance
You are falling into a common pitfall when using velocity with spring : you place your templates in one location and use a resource loader that searches them in another place. So you have 2 common usages :
put templates in classpath (as you do) and use ClasspathResourceLoader
resource.loader = class
class.resource.loader.class = org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
it is simple with little dependencies, but it forces you to put templates in classpath ...
put templates under WEB-INF (as you would do for JSPs) and use WebappResourceLoader from velocity tools
resource.loader=webapp
webapp.resource.loader.class=org.apache.velocity.tools.view.WebappResourceLoader
webapp.resource.loader.path=/WEB-INF/velocity/
it is more natural for a template location, but you add a dependency on velocity tools.
And let spring manage dependencies but not instanciating via new ...
I had the same problem recently with karaf OSGi framework.
In a CXF resource class (Login in this context) you have to initialize the Velocity Engine like this:
public Login() {
/* first, get and initialize an engine */
ve = new VelocityEngine();
ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
ve.init();
}
Then, in the web method, instantiate the template:
/* create a context and add data */
synchronized (initLock) {
if (loginTemplate == null) {
loginTemplate = ve.getTemplate("templates/login.vm");
}
}
VelocityContext context = new VelocityContext();
Unfortunately, it didn't work out to load the template immediately after the ve.init() call in the constructor.
Your configuration seems correct. If you instantiate the VelocityEngine instance using "new", try following:
#Autowired
VelocityEngine velocityEngine;