Whitelabel Error Page error (Spring Boot + React) - reactjs

localhost:9000 is opening fine on the browser. And if I navigate to a link from the menu like localhost:9000/about, it is working fine.
But if I hit localhost:9000/about directly without going to localhost:9000 then nothing happens on the local and if I do the same on server, following error is produced:
Whitelabel Error Page This application has no explicit mapping for
/error, so you are seeing this as a fallback.
Mon Feb 12 14:09:05 IST 2018 There was an unexpected error (type=Not
Found, status=404). No message available
Please help!!

This is happening because in your application you have not defined what your application should do when it will get url request localhost:9000.
For every Request mapping you need to define the operation you want to perform. In your case for localhost:9000 you have to write what you want to do as you have done for local:9000/about.
#RequestMapping("")
#ResponseBody
Function_For_HandlingRequest{}

When you hit http://localhost:9090/about directly, SpringBoot redirect To a /login.html.
So, Redirect every page to index.html .
https://github.com/geowarin/boot-react/blob/master/backend/src/main/java/react/config/SinglePageAppConfig.java
The WebMvcConfigurer interface, starting with Spring 5, contains default implementations for all its methods. As a result, the abstract adapter (WebMvcConfigurerAdapter) class was marked as deprecated.
package your.package.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.resource.ResourceResolver;
import org.springframework.web.servlet.resource.ResourceResolverChain;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
/**
* Redirects every page to index.html
* Used to handle the router
*/
#Configuration
public class SinglePageAppConfig implements WebMvcConfigurer {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/static/")
.resourceChain(false)
.addResolver(new PushStateResourceResolver());
}
private class PushStateResourceResolver implements ResourceResolver {
private Resource index = new ClassPathResource("/static/index.html");
private List<String> handledExtensions = Arrays.asList("html", "js", "json", "csv", "css", "png", "svg", "eot", "ttf", "woff", "appcache", "jpg", "jpeg", "gif", "ico");
private List<String> ignoredPaths = Arrays.asList("api");
#Override
public Resource resolveResource(HttpServletRequest request, String requestPath, List<? extends Resource> locations, ResourceResolverChain chain) {
return resolve(requestPath, locations);
}
#Override
public String resolveUrlPath(String resourcePath, List<? extends Resource> locations, ResourceResolverChain chain) {
Resource resolvedResource = resolve(resourcePath, locations);
if (resolvedResource == null) {
return null;
}
try {
return resolvedResource.getURL().toString();
} catch (IOException e) {
return resolvedResource.getFilename();
}
}
private Resource resolve(String requestPath, List<? extends Resource> locations) {
if (isIgnored(requestPath)) {
return null;
}
if (isHandled(requestPath)) {
return locations.stream()
.map(loc -> createRelative(loc, requestPath))
.filter(resource -> resource != null && resource.exists())
.findFirst()
.orElseGet(null);
}
return index;
}
private Resource createRelative(Resource resource, String relativePath) {
try {
return resource.createRelative(relativePath);
} catch (IOException e) {
return null;
}
}
private boolean isIgnored(String path) {
return ignoredPaths.contains(path);
}
private boolean isHandled(String path) {
String extension = StringUtils.getFilenameExtension(path);
return handledExtensions.stream().anyMatch(ext -> ext.equals(extension));
}
}
}

in Application
#Bean
public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer() {
return factory -> {
ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/index.html");
factory.addErrorPages(error404Page);
};
}
enter image description here

Related

Parameter 0 of constructor in ... required a bean of type... that could not be found

I'm walking through a pivotal 'guide' project, my first time uploading files in Spring.
I've implemented the code exactly as the guide specifies but still am getting the following error:
Parameter 0 of constructor in hello.storage.FileSystemStorageService required a bean of type 'hello.storage.StorageProperties' that could not be found.
Consider defining a bean of type 'hello.storage.StorageProperties' in your configuration.
I've reviewed many so posts and it seems the common thread is to move my 'application' class to the root package, but its already there. Here is my project:
UploadingFiles1Application.java
package hello;
// multiple imports
#SpringBootApplication
public class UploadingFiles1Application {
public static void main(String[] args) {
SpringApplication.run(UploadingFiles1Application.class, args);
}
#Bean
CommandLineRunner init(StorageService storageService) {
return (args) -> {
storageService.deleteAll();
storageService.init();
};
}
}
And here's my Service:
package hello.storage;
import org.springframework.core.io.Resource;
import org.springframework.web.multipart.MultipartFile;
import java.nio.file.Path;
import java.util.stream.Stream;
public interface StorageService {
void init();
void store(MultipartFile file);
Stream<Path> loadAll();
Path load(String filename);
Resource loadAsResource(String filename);
void deleteAll();
}
And its implementation:
package hello.storage;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.stream.Stream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.util.FileSystemUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
#Service
public class FileSystemStorageService implements StorageService {
private final Path rootLocation;
#Autowired
public FileSystemStorageService(StorageProperties properties) {
this.rootLocation = Paths.get(properties.getLocation());
}
#Override
public void store(MultipartFile file) {
String filename = StringUtils.cleanPath(file.getOriginalFilename());
try {
if (file.isEmpty()) {
throw new StorageException("Failed to store empty file " + filename);
}
if (filename.contains("..")) {
// This is a security check
throw new StorageException(
"Cannot store file with relative path outside current directory "
+ filename);
}
try (InputStream inputStream = file.getInputStream()) {
Files.copy(inputStream, this.rootLocation.resolve(filename),
StandardCopyOption.REPLACE_EXISTING);
}
}
catch (IOException e) {
throw new StorageException("Failed to store file " + filename, e);
}
}
#Override
public Stream<Path> loadAll() {
try {
return Files.walk(this.rootLocation, 1)
.filter(path -> !path.equals(this.rootLocation))
.map(this.rootLocation::relativize);
}
catch (IOException e) {
throw new StorageException("Failed to read stored files", e);
}
}
#Override
public Path load(String filename) {
return rootLocation.resolve(filename);
}
#Override
public Resource loadAsResource(String filename) {
try {
Path file = load(filename);
Resource resource = new UrlResource(file.toUri());
if (resource.exists() || resource.isReadable()) {
return resource;
}
else {
throw new StorageFileNotFoundException(
"Could not read file: " + filename);
}
}
catch (MalformedURLException e) {
throw new StorageFileNotFoundException("Could not read file: " + filename, e);
}
}
#Override
public void deleteAll() {
FileSystemUtils.deleteRecursively(rootLocation.toFile());
}
#Override
public void init() {
try {
Files.createDirectories(rootLocation);
}
catch (IOException e) {
throw new StorageException("Could not initialize storage", e);
}
}
}
What am I missing??
Thanks in advance.
First of all i do not know if your StorageProperties is a spring component or just a simple java class!
I am going to suppose that it is a spring component :
#Component
public class StorageProperties {
...
}
In the FileSystemStorageService, you replace the constructor by a postConstruct method :
#Service
public class FileSystemStorageService implements StorageService {
private Path rootLocation;
#Autowired
StorageProperties properties;
#PostConstruct
public void FileSystemStorageService() {
this.rootLocation = Paths.get(properties.getLocation());
....
}

how to create CXF API for jbilling integration?

Can anyone tell me how to create CXF API? For jbilling integration, I want to create CXF API. But I don't know how to create it.
you can create a class in jbilling which call other evn and send headers and body as Json or string.
like this.
package com.cycle30.plugin.payment;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.log4j.Logger;
public class HttpJMSClient {
private PostMethod postMethod;
private String webUrl;
private List<NameValuePair> nameValuePairs=new ArrayList<NameValuePair>();
private static final Logger logger = Logger.getLogger(HttpJMSClient.class);
public HttpJMSClient() {
// TODO Auto-generated constructor stub
}
public void getConnection()
{
webUrl="http://localhost:8081";
nameValuePairs.add(new NameValuePair("x-force-user-id","abc1233"));
nameValuePairs.add(new NameValuePair("x-trans-id","123"));
}
public String makeCall( String body)
{
Object output=null;
try{
WebClient client = WebClient.create(webUrl);
for (NameValuePair h : nameValuePairs) {
client.header(h.getName(), h.getValue());
}
Response response = client.type(MediaType.APPLICATION_JSON).post(body,
Response.class);
logger.debug("Output from Server .... \n");
output = response.getEntity();
logger.debug(output);
System.out.println("my res: "+output.toString());
int statusCode = response.getStatus();
System.out.println("status code: "+statusCode);
return output.toString();
}catch(Exception e){
logger.error(e.getMessage());
logger.error(e.getCause());
}
return output.toString();
}
}

Google App Engine (GAE) message.getContent() using javamail and IMAP not works

I have several days trying to get the contents of a message through IMAP on a Google App Engine Project.
I managed to extract all the other information, but to extract the contents of jumps me an error message (not work even invoking message.getContent.tostring(), I've tried as MultiPart).
I perform the same action from a normal project , (not GAE and using javamail.1.4.7), the content of the messages shown perfectly.
This is the code of GAE project:
import java.util.Properties;
import java.util.logging.Logger;
import javax.mail.Session;
import java.io.IOException;
import javax.mail.Authenticator;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Store;
import javax.servlet.http.*;
#SuppressWarnings("serial")
public class nuevo extends HttpServlet {
private String User;
private String Pass;
private static final Logger log = Logger.getLogger(nuevo.class
.getName());
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
User = "User";
Pass = "Pass";
LlamaIMAP(resp);
}
public void LlamaIMAP(HttpServletResponse resp) {
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
props.put("mail.imap.host", "imap.gmail.com");
props.put("mail.imap.user", User);
props.put("mail.imap.socketFactory", 993);
props.put("mail.imap.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.imap.port", 993);
Session session = Session.getDefaultInstance(props,
new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(User, Pass);
}
});
try {
Store store = session.getStore("imap");
store.connect("imap.gmail.com", 993, User, Pass);
Folder fldr = store.getFolder("Inbox");
fldr.open(Folder.HOLDS_MESSAGES);
// HOLDS_MESSAGES);
Message[] ar = fldr.getMessages();
int count = fldr.getMessageCount();
resp.getWriter().println(count);
resp.getWriter().println(ar[0].getAllRecipients()[0].toString());
resp.getWriter().println(ar[0].getFrom()[0].toString());
resp.getWriter().println(ar[0].getSentDate().toString());
resp.getWriter().println(ar[0].getSubject());
resp.getWriter().println(ar[0].getContent().toString());
} catch (Exception exc) {
try {
resp.getWriter().println(exc + "error");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
I managed to fix it.
Only you need to add this lines to the appengine-web.xml configuration file:
<class-loader-config>
<priority-specifier filename="imap.jar"/>
<priority-specifier filename="gimap.jar"/>
<priority-specifier filename="dsn.jar"/>
<priority-specifier filename="mailapi.jar"/>
</class-loader-config>
Thanks.

injecting Session bean from another session bean in JBoss 7.1

I am not able to inject a SLSB in another SLSB. Actually created 3 projects
1) created a EJB project with an MDB
2) created a EJB project with a stateless session bean for posting the message
3) created a EJB project with a stateless session bean for injecting the above session bean
But while injecting I am not able to inject the EJB it is returning null
the code is as below
1) MDB:
#MessageDriven(
activationConfig = {
#ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
#ActivationConfigProperty(propertyName = "destination", propertyValue = "activemq/queue/TestQueue"),
#ActivationConfigProperty(propertyName="acknowledgeMode", propertyValue="Auto-acknowledge")
})
#ResourceAdapter("activemq-ra.rar")
public class ConsumerMDB implements MessageListener {
public void onMessage(Message message) {
try {
System.out.println("Queue: Received a TextMessage at " + new Date());
TextMessage msg = (TextMessage) message;
System.out.println("Message is : " + msg.getText());
} catch (JMSException e) {
e.printStackTrace();
}
}
}
2) Session Bean 1
package com.springboard.session;
import javax.annotation.Resource;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.jms.JMSException;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.TextMessage;
#Stateless
#LocalBean
public class ProducerSession implements ProducerSessionLocal {
#Resource(mappedName="java:jboss/activemq/QueueConnectionFactory")
public static QueueConnectionFactory factory;
#Resource(mappedName = "java:jboss/activemq/queue/TestQueue")
public static Queue queue;
#Override
public void sendMessage(String msg) {
System.out.println("****************Entering into method********************");
try {
System.out.println(queue.getQueueName());
QueueConnection qConnection = factory.createQueueConnection();
QueueSession qSession = qConnection.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
TextMessage message = qSession.createTextMessage();
message.setText(msg);
QueueSender qSender = qSession.createSender(queue);
qSender.send(message);
qSender.close();
qSession.close();
qConnection.close();
} catch (JMSException e) {
e.printStackTrace();
}
System.out.println("****************Exiting into method********************");
}
}
and the interface is
package com.springboard.session;
import javax.ejb.Local;
#Local
public interface ProducerSessionLocal {
public void sendMessage(String msg);
}
3) Second session bean to inject the first session
#Stateless
public class TestProducerLocalBean implements TestProducerLocalBeanLocal {
#EJB(mappedName = "java:global/ProducerSessionActiveMQ/ProducerSession!com.springboard.session.ProducerSessionLocal")
public ProducerSessionLocal producer;
public TestProducerLocalBean() {
System.out.println("*************Testing Producer****************");
if(producer!=null){
producer.sendMessage("This Message is from SessionBean to Session Bean to MDB");
}
else{
System.out.println("EJB is null");
}
System.out.println("**********End************************");
}
#Override
public void messageSend(String msg) {
// TODO Auto-generated method stub
}
and for testing purpose used a class
import javax.ejb.EJB;
import com.springboard.session.test.TestProducerLocalBean;
public class testEJB {
#EJB
public static TestProducerLocalBean local =new TestProducerLocalBean();
public static void main(String[] args) {
}
}
At producer EJB always retuns null. With using servlet to inject ProducerSession i am able to do it. but injecting with another EJB i not able to get it.
Could any one please help me out what i am missing
Thanks in advance
It's incorrect to use initialization ... = new Xyz() when using injection because initialization of those fields is the responsibility of the container. You probably attempted that because you noticed that the field was null, and that's because injection (including #EJB) is not supported in the main class unless you use an application client container.

JSF file upload on GAE

I'm trying to have a file upload element in my JSF over Google App Engine.
I have browsed the web for several alternatives but none seem to work with GAE.
I was able to do so using JSP and servlet with BlobstoreService but couldn't find a way to make it working with JSF.
As a workaround I was trying to see if there is a way to include a JSP within a JSF but I guess this isn't doable as well.
Would be thankful to get a working example.
Thanks!
First get library http://code.google.com/p/gmultipart/ and add to your project.
And than override class org.primefaces.webapp.filter.FileUploadFilter (just put in your src).
There is code of class org.primefaces.webapp.filter.FileUploadFilter:
package org.primefaces.webapp.filter;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.gmr.web.multipart.GFileItemFactory;
import org.primefaces.webapp.MultipartRequest;
public class FileUploadFilter implements Filter {
private final static Logger logger = Logger.getLogger(FileUploadFilter.class.getName());
private final static String THRESHOLD_SIZE_PARAM = "thresholdSize";
private final static String UPLOAD_DIRECTORY_PARAM = "uploadDirectory";
private String thresholdSize;
private String uploadDir;
public void init(FilterConfig filterConfig) throws ServletException {
thresholdSize = filterConfig.getInitParameter(THRESHOLD_SIZE_PARAM);
uploadDir = filterConfig.getInitParameter(UPLOAD_DIRECTORY_PARAM);
if(logger.isLoggable(Level.FINE))
logger.fine("FileUploadFilter initiated successfully");
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
boolean isMultipart = ServletFileUpload.isMultipartContent(httpServletRequest);
if(isMultipart) {
if(logger.isLoggable(Level.FINE))
logger.fine("Parsing file upload request");
//start change
FileItemFactory diskFileItemFactory = new GFileItemFactory();
/* if(thresholdSize != null) {
diskFileItemFactory.setSizeThreshold(Integer.valueOf(thresholdSize));
}
if(uploadDir != null) {
diskFileItemFactory.setRepository(new File(uploadDir));
}*/
//end change
ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
MultipartRequest multipartRequest = new MultipartRequest(httpServletRequest, servletFileUpload);
if(logger.isLoggable(Level.FINE))
logger.fine("File upload request parsed succesfully, continuing with filter chain with a wrapped multipart request");
filterChain.doFilter(multipartRequest, response);
} else {
filterChain.doFilter(request, response);
}
}
public void destroy() {
if(logger.isLoggable(Level.FINE))
logger.fine("Destroying FileUploadFilter");
}
}
In managed bean write method like:
public void handleFileUpload(FileUploadEvent event) {
UploadedFile uploadedFile = event.getFile();
try {
String blobKey = BlobUtils.uploadImageToBlobStore(uploadedFile.getContentType(), uploadedFile.getFileName(), uploadedFile.getContents());
this.iconKey = blobKey;
} catch (IOException e) {
log.log(Level.SEVERE, "Ошибка при попытке загрузить файл в blob-хранилище", e);
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Ошибка при попытке загрузить файл", event.getFile().getFileName() + " не загружен!");
FacesContext.getCurrentInstance().addMessage(null, msg);
return;
}
FacesMessage msg = new FacesMessage("Успешно.", event.getFile().getFileName() + " загружен.");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
And that all.
First of all , I think that whatever you are doing with JSP should eventually work with JSF as well..
BUT,
If you are looking for a file upload component for JSF , that works on GAE ,
take a look at the PrimeFaces FileUpload
Here is another link that got an explanation on what to do in order it to work on GAE :Primefaces File Upload Filter
(haven't tried it myself...)

Resources