When I Implement primefaces FileDownload Class which is in Primefaces UserGuide at this point my IDE showing set method return type to void or change to constructor.
public FileDownloadController()
public class FileBean {
private StreamedContent file;
public FileDownloadController() {
InputStream stream = this.getClass().getResourceAsStream("yourfile.pdf");
file = new DefaultStreamedContent(stream, "application/pdf",
"downloaded_file.pdf");
}
public StreamedContent getFile() {
return this.file;
}
}
what is the exact problem.
that is because your class has a different name, to solve this change
public FileDownloadController() to public FileBean()
change your code to like this..
package org.primefaces.examples.view;
public class FileDownloadController {
private StreamedContent file;
public FileDownloadController() {
InputStream stream = ((ServletContext)FacesContext.getCurrentInstance().getExternalContext().getContext()).getResourceAsStream("/images/optimusprime.jpg");
file = new DefaultStreamedContent(stream, "image/jpg", "downloaded_optimus.jpg");
}
public StreamedContent getFile() {
return file;
}
}
Related
public class PersistenceManager {
public boolean addUser(User user) {
UserPersistor userPersistor = new UserPersistor(user) {
#Override
void somemethod() {
// TODO Auto-generated method stub
}
};
userPersistor.addUser();
System.out.println("PersistenceManager added user ");
return true;
}
class User {
public String firstName;
public String lastName;
public User(String firstName, String lastName) {
super();
this.firstName = firstName;
this.lastName = lastName;
}
}
abstract class UserPersistor {
public UserPersistor( ) {
}
public UserPersistor(User user) {
}
public void addUser() {
System.err.println("UserPersistor added user ");
}
abstract void somemethod();
}
}
import static org.powermock.api.easymock.PowerMock.createMock;
import static org.powermock.api.easymock.PowerMock.expectNew;
import static org.powermock.api.easymock.PowerMock.expectLastCall;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
#RunWith(PowerMockRunner.class)
#PrepareForTest( PersistenceManager.class )
public class PersistenceManagerTest {
private User user = null;
#Before
public void before() throws Exception {
user = createMock(User.class);
UserPersistor userPersistor = createMock(UserPersistor.class);
userPersistor.addUser();
expectLastCall();
expectNew(UserPersistor.class, user).andReturn(userPersistor);
PowerMock.replayAll();
}
#Test
public void testaddUser() {
PersistenceManager tested = new PersistenceManager();
tested.addUser(user);
PowerMock.verifyAll();
}
}
Whats wrong with above code? I dont see mocked object for UserPersistor. Meaning, i dont want to see "UserPersistor added user " printed. It should not do anything. But it is printing it since real object of UserPersistor is created. I am facing this problem in my actual project, thought would simulate and try to solve in a much smaller context. But I am stumped.
That's because you are not expecting to instantiate UserPersistor but an anonymous inner class extending UserPersistor.
To do that you need to retrieve that class, mock it and expect it. PowerMock has a Whitebox class to do that. You are exposing the class implementation when using it. I would recommend that you refactor your code to inject the code instead. But if you really want to, you should write this:
#Before
public void before() throws Exception {
user = createMock(PersistenceManager.User.class);
Class<Object> clazz = Whitebox.getAnonymousInnerClassType(PersistenceManager.class, 1);
PersistenceManager.UserPersistor userPersistor = createMock(clazz);
userPersistor.addUser();
expectNew(clazz, user).andReturn(userPersistor);
PowerMock.replayAll();
}
I have camel route as below
public class IncomingBatchFileRoute extends RouteBuilder {
#Value(CCS_PROCESSING_INCOMING_DIRECTORY)
private String source;
#Override
public void configure() throws Exception {
from(sourceLocation)).autoStartup(false).to("encryptionEndPoint");
}
}
I need to write a JUNIT For above camel route and am new to it and created a structure as below
public class IncomingBatchFileRouteTest extends CamelTestSupport{
#Override
public RoutesBuilder createRouteBuilder() throws Exception {
return new IncomingBatchFileRoute();
}
#Test
public void sampleMockTest() {
}
}
Not sure how to complete it. Request you to help me on this
You need to mock your encryptionEndPoint and start your route with a producerTemplate
#Produce(uri = CCS_PROCESSING_INCOMING_DIRECTORY)
protected ProducerTemplate template;
#EndpointInject(uri = "encryptionEndPoint")
protected MockEndpoint resultEndpoint;
#Test
public void sampleMockTest() {
// GIVEN
this.resultEndpoint.expectedMessageCount(1);
// WHEN
this.template.sendBody("Hey");
// THEN
this.resultEndpoint.assertIsSatisfied();
}
Maybe the title is not the best to explain the problem, but I'll try to explain it as best as possible.
I have an Spring Boot Application using JPA and MySQL, so in order to check everything worked properly, I made a simple CRUD test for my database, and I found problems with autowiring which are explained in my previous question. The solution for those problems was just adding the #ComponentScan annotation to my Application.java.
It was the solution for the test because it run without problems, but then I find another problem. Apart from the test, I need my application to show a list of Proposals made by some Users and also some Comments. Before adding that annotation, the HTMLs showed the correct information, but after adding it shows information about the database in JSON format on the main page and if I try to navigate to "localhost:8080/viewProposal" p.e. it shows a WhiteLabel error page with error code 404. I have no idea why it is replacing the HTMLs because I have just one controller and is not a RESTController. These are my classes:
Application.java
#SpringBootApplication
#EntityScan("persistence.model")
#EnableJpaRepositories("persistence.repositories")
#ComponentScan("services.impl")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
MainController.java
#Controller
#RequestMapping("/")
public class MainController {
private static final Logger logger = Logger.getLogger(MainController.class);
private List<SseEmitter> sseEmitters = Collections.synchronizedList(new ArrayList<>());
private Map<String, Proposal> proposals = generateProposals();
#RequestMapping({"/live","/"})
public String landing(Model model) {
return "index";
}
#RequestMapping("/viewProposal")
public String viewProposal(Model model, Long id) {
//put the object in the map
return "viewProposal";
}
#KafkaListener(topics = "newVote")
public void listen(String data) {
String[] contents = data.split(";");
if(contents.length!=2)
return;
Proposal p;
int newVote;
if (proposals.containsKey(contents[0]))
p = proposals.get(contents[0]);
else {
p = new Proposal();
p.setTitle(contents[0]);
proposals.put(p.getTitle(), p);
}
if (contents[1].equals("+"))
newVote = +1;
else if (contents[1].equals("-"))
newVote = -1;
else
newVote = 0;
p.setNumberOfVotes(p.getNumberOfVotes() + newVote);
logger.info("New message received: \"" + data + "\"");
}
private static Map<String, Proposal> generateProposals() {
Map<String, Proposal> lista = new HashMap<String, Proposal>();
Proposal p = new Proposal();
p.setTitle("tituloPrueba");
lista.put("tituloPrueba", p);
return lista;
}
#ModelAttribute("proposals")
public Map<String, Proposal> getProposals() {
return proposals;
}
public void setProposals(Map<String, Proposal> proposals) {
this.proposals = proposals;
}
}
MvcConfiguration
#Configuration
#EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter{
#Bean
public ViewResolver getViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/resources/templates/");
resolver.setSuffix(".html");
return resolver;
}
#Override
public void configureDefaultServletHandling(
DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.defaultContentType(MediaType.TEXT_HTML);
}
}
If you want to see the rest of the classes, please go to my previous question everything is in there.
Thanks in advance.
Its a legacy code which I am not able to unit test using Powermock. Kindly help me in unit test below class using Powermock or any other way if there is any:
ServiceAPI class has to be unit tested
public class ServiceAPI {
public String getServiceKey(String serviceNumber){
String jndiUrl = getServURL();
return jndiUrl;
}
public String getServURL(){
String url = ServiceLocator.getInstance().init();
return url;
}
}
Above class has dependency on below class which has to be mocked
public class ServiceLocator {
private static ServiceLocator serviceLocator = new ServiceLocator();
public static ServiceLocator getInstance(){
return serviceLocator;
}
public String init(){
return "Jndi Call has return fix name";
}
}
I have written below test
#RunWith(PowerMockRunner.class)
#PrepareForTest(ServiceLocator.class)
public class ServiceAPITest {
#Test
public void testGetServiceKey() {
ServiceLocator serviceLocator = PowerMockito.mock(ServiceLocator.class);
PowerMockito.mockStatic(ServiceLocator.class);
PowerMockito.when(ServiceLocator.getInstance()).thenReturn(serviceLocator);
PowerMockito.when(serviceLocator.init()).thenReturn("value");
ServiceAPI serviceAPI = new ServiceAPI();
serviceAPI.getServiceKey("20156");
}
}
Not getting o/p. Please help!
I run this at the application Start Up
public class ConfigurationFacility : AbstractFacility {
private readonly List<string> configuredComponents = new List<string>();
protected override void Init() {
Kernel.ComponentRegistered += OnComponentRegistered;
// add environment configurators
}
private void OnComponentRegistered(string key, IHandler handler) {
// if the component is a configurator then run conf settings and add it to configuredComponents
}}
Question: How to hook tear down and to call explicit release for each ?
Thanks
You can use either the ComponentDestroyed event of IKernel or just implement IDisposable in your components. Here's a little sample code:
namespace WindsorInitConfig {
[TestFixture]
public class ConfigurationFacilityTests {
[Test]
public void tt() {
OneDisposableComponent component = null;
using (var container = new WindsorContainer()) {
container.AddFacility<ConfigurationFacility>();
container.AddComponent<OneDisposableComponent>();
component = container.Resolve<OneDisposableComponent>();
}
Assert.IsTrue(component.Disposed);
Assert.Contains(component, ConfigurationFacility.DestroyedComponents);
}
public class OneDisposableComponent : IDisposable {
public bool Disposed { get; private set; }
public void Dispose() {
Disposed = true;
}
}
public class ConfigurationFacility : AbstractFacility {
private readonly List<string> configuredComponents = new List<string>();
public static readonly ArrayList DestroyedComponents = new ArrayList();
protected override void Init() {
Kernel.ComponentRegistered += OnComponentRegistered;
Kernel.ComponentDestroyed += Kernel_ComponentDestroyed;
// add environment configurators
}
private void Kernel_ComponentDestroyed(ComponentModel model, object instance) {
DestroyedComponents.Add(instance);
// uninitialization, cleanup
}
private void OnComponentRegistered(string key, IHandler handler) {
// if the component is a configurator then run conf settings and add it to configuredComponents
configuredComponents.Add(key);}
}
}
}
The static ArrayList is only for demo purposes, of course.