Spring Service doesn't answer - java

I have to create a new rest service, the problem is my service never answer and never logs.
On the the same app I have this following service class which works properly.
I mean on the browser (under this url http://localhost:8080/IMEL/resources/hello ) answers correctly "Hello from IMEL Rest service!"
package it.sella.imel.api.rest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.springframework.stereotype.Service;
#Service
#Path("/hello")
public class HelloService {
#GET
#Produces({MediaType.TEXT_PLAIN})
public String hello() {
return "Hello from IMEL Rest service!";
}
}
While my new service doesn't log and responds (at this url http://localhost:8080/IMEL/resources/listapwg ) the following error "{"status":"EXPECTATION_FAILED","errorMessage":"HTTP 404 Not Found"}"
package src.main.java.it.sella.imel.api.rest;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import org.springframework.stereotype.Service;
import it.sella.imel.api.model.TransazioneConstants;
import it.sella.imel.api.model.TransazioneSingola;
import it.sella.imel.db.DbManager;
import it.sella.imel.util.ImelConstants;
import it.sella.util.Log4Debug;
import it.sella.util.Log4DebugFactory;
import it.sella.imel.api.log.Logged;
#Service
#Logged
#Path("/listapwg")
public class ListaPWG {
private static Log4Debug log4Debug = Log4DebugFactory.getLog4Debug(ListaPWG.class);
#GET
#Produces({MediaType.TEXT_PLAIN})
public String helloListaPWG() {
log4Debug.debug("sono in helloListaPWG GET");
return "Hello from IMEL Rest service!";
}
#POST
#Produces({ MediaType.APPLICATION_JSON })
public Response fetchListaPWG(#QueryParam("dataQuadratura") String dataQuadratura, #Context UriInfo uriInfo) {
log4Debug.debug("sono in fetchListaPWG POST");
... do some other stuff ...
return Response.status(Response.Status.OK).entity(entity).build();
}
}
obviously maven compiles correctly...
the only difference I see is the Logged class, but within or without, in any case it won't work, that's why I don't think that is the problem.
package it.sella.imel.api.log;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.ws.rs.NameBinding;
#NameBinding
#Retention(RUNTIME)
#Target({ElementType.TYPE, ElementType.METHOD})
public #interface Logged {
}

Related

Resolved [org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'file' is not present]

I am getting the error
"Resolved[org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'file' is not present]"
I tried all the options provided on previous posts it didn't work please tell me what I am doing wrong this is my first spring-boot application.
My controller
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import java.io.File;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
#RestController
public class SpringBootJdbcController {
#Autowired
JdbcTemplate jdbc;
#Autowired
private SpringBootJdbcService springBootJdbcService;
#RequestMapping("/insert")
public String index() {
jdbc.execute("insert into user(name,email)values('javatpoint','java#javatpoint.com')");
return "data inserted Successfully";
}
#CrossOrigin(origins = "http://localhost:4200")
#ResponseStatus(HttpStatus.OK)
#RequestMapping(value = "/uploadFile", method = RequestMethod.POST, consumes = "multipart/form-data")
public void uploadFiles(#RequestParam("file") MultipartFile file) throws Exception {
System.out.println("hello hello hello");
System.out.println("file---------" + file);
springBootJdbcService.readConfigData(file);
}
}
My Application.properties
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=11MB
api call postman image :-
I don't understand what is the problem. Its my first spring-boot application please help.

SpringBoot REST Controller throws "can not have an entity parameter error"

I have the following Spring Boot Controller:
import java.io.InputStream;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.att.aft.dme2.internal.javaxwsrs.PUT;
import com.att.bttw.model.HelloWorld;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
#Api
#Path("/service")
#Produces({ MediaType.APPLICATION_JSON })
public interface RestService {
#PUT
#Path("/datarouter/{filename}")
#Consumes("application/gzip")
#Produces(MediaType.APPLICATION_JSON)
Response testEndpoint(#Context HttpServletRequest request, #PathParam("filename") String filename, InputStream inputStream);
}
The implementation of this method is simply:
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.Response;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.client.RestTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import com.att.bttw.model.ApplicationResults;
import com.att.bttw.model.CountsDataModel;
import com.att.bttw.model.CountsDataResults;
import com.att.bttw.model.DisplayFieldRecord;
import com.att.bttw.model.DisplayRecord;
import com.att.bttw.model.WatermarkEventObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
#Override
public Response testEndpoint(HttpServletRequest request, String filename, InputStream inputStream) {
System.out.println("File name consumed: " + filename);
return null;
}
When I try to hit this endpoint, I get the following error:
"Following issues have been detected: Response testEndpoint(javax.servlet.http.HttpServletRequest, java.lang.String, java.io.InputStream), can not have an entity parameter. Try to move the parameter to the corresponding resource method".
When I remove the InputStream and HttpServletRequest parameters, the endpoint works just fine, I'm just not understanding the error message I'm getting.

Issue with responseEntity . MockMvc.Perform() gives 200 status code even if the ResponseEntity.HttpStatus is 201

Im trying to mock a controller's post method. I want it to return status code 201(CREATED) . But it gives Status Code 200.
Given below is the code
This is my controller Class
package com.example.demo;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
public #RestController
class SomeController{
#PostMapping("/insertString")
public ResponseEntity<String> insertString(String str) {
return new ResponseEntity<>(new String("monster"),HttpStatus.CREATED);
}
}
This is my junit test Suit
package com.example.demo;
import static org.junit.Assert.*;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.mockito.Mockito.anyString;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
#RunWith(SpringRunner.class)
#WebMvcTest(SomeController.class)
public class TestClass {
#Autowired
private MockMvc mockMvc;
#MockBean
private SomeController someController;
#Test
public void test() throws Exception {
ResponseEntity<String> entity = new ResponseEntity<>(HttpStatus.CREATED);
when(someController.insertString(anyString())).thenReturn(entity);
RequestBuilder requestBuilder = MockMvcRequestBuilders
.post("/insertString")
.accept(MediaType.APPLICATION_JSON)
.content("monkey")
.contentType(MediaType.APPLICATION_JSON);
MvcResult result = mockMvc.perform(requestBuilder)
.andExpect(status().isCreated())
.andReturn();
System.out.println(result.getResponse().getContentAsString());
}
}
The errorim getting is
java.lang.AssertionErrror:Status expected:<201> but was:<200>
Though i have mentioned the status as HttpStatus.CREATED in the RequestEntity object, Why am i getting 200.
Please if someone can help
Try to change
public ResponseEntity<String> insertString(String str)
to
public ResponseEntity<String> insertString(#RequestBody String str)
I've run the test with above code and it passed.

not org.apache.hadoop.mapreduce.Mapper

I am writing a mapreduce project.
I want to send an array from mapper to reducer.
But it has an error and I can't fix It.
I import these classes:
import java.io.DataInput;
import java.io.DataOutput;
import java.io.EOFException;
import java.io.IOException;
import java.net.Socket;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.hadoop.conf.Configured;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.util.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.Iterator;
import hadoop.DENCLUE;
//import javafx.scene.text.Text;
import sun.security.krb5.Config;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.viewfs.Constants;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.hadoop.mapred.FileOutputFormat;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.MapReduceBase;
import org.apache.hadoop.mapred.Mapper;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reducer;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.mapred.TextInputFormat;
import org.apache.hadoop.mapred.TextOutputFormat;
//import org.apache.hadoop.mapred.jobcontrol.Job;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.omg.CORBA.PUBLIC_MEMBER;
import com.sun.org.apache.bcel.internal.generic.NEW;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.*;
import org.apache.hadoop.mapreduce.lib.output.*;
import org.apache.hadoop.mapreduce.Mapper.Context;
import org.apache.hadoop.mapreduce.task.JobContextImpl;
import org.apache.hadoop.mapreduce.lib.input.*;
import org.apache.hadoop.mapreduce.lib.output.*;
import org.apache.hadoop.util.*;
import java.io.DataOutput;
import java.io.DataInput;
import java.io.IOException;
This is my Map class:
public static class Mapn extends MapReduceBase implements Mapper<LongWritable, Text, Text, Text> {
#SuppressWarnings("rawtypes")
Context con ;
#SuppressWarnings("unchecked")
public void map(LongWritable key, Text value, OutputCollector< Text,Text >
output, Reporter reporter) throws IOException {
String line = value.toString();
String[] words=line.split(",");
for(String word: words )
{
Text outputKey = new Text(word.toUpperCase().trim());
try {
con.write(outputKey, words);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
This is the job:
public static void main(String[] args) throws Exception {
Configuration c=new Configuration();
String[] files=new GenericOptionsParser(c,args).getRemainingArgs();
Path input=new Path(files[0]);
Path output=new Path(files[1]);
Job j=new Job(c,"wnt");
j.setJarByClass(projectmr.class);
j.setMapperClass(Mapn.class);
j.setReducerClass(Reduce.class);
j.setOutputKeyClass(Text.class);
j.setOutputValueClass(Text.class);
FileInputFormat.addInputPaths(j, input);
FileOutputFormat.setOutputPath(j, output);
System.exit(j.waitForCompletion(true)?0:1);
and this is the error I get:
Exception in thread "main" java.lang.RuntimeException: class hadoop.projectmr$Mapn not org.apache.hadoop.mapreduce.Mapper
at org.apache.hadoop.conf.Configuration.setClass(Configuration.java:1969)
at org.apache.hadoop.mapreduce.Job.setMapperClass(Job.java:891)
at hadoop.projectmr.main(projectmr.java:191)
This is the old, Hadoop 1 API
import org.apache.hadoop.mapred.*;
You should be importing from classes within
org.apache.hadoop.mapreduce.*;
As the error says
not org.apache.hadoop.mapreduce.Mapper
So, basically, you don't need MapReduceBase, and Mapper is a class now, not an interface
So, you now would have
public static class MyMapper extends Mapper<Kin, Vin, Kout, Vout>
Look at the WordCount code

java.io.FileNotFoundException: Could not open ServletContext resource [/application.properties]

org.springframework.beans.factory.BeanDefinitionStoreException: Failed to parse configuration class [com.gaian.adwize.ssp.main.SSPStarter]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/application.properties] at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:187) at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:324) at
Test class
----------
package com.gaian.adwize.swagger;
import com.gaian.adwize.ssp.main.SSPStarter;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import java.io.BufferedWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.springframework.context.annotation.ImportResource;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
#WebAppConfiguration
#RunWith(SpringJUnit4ClassRunner.class)
#AutoConfigureRestDocs(outputDir = "build/asciidoc/snippets")
#SpringBootTest(classes = {SSPStarter.class, SwaggerConfig.class})
#AutoConfigureMockMvc
public class Swagger2MarkupTest {
private static final Logger LOG = LoggerFactory.getLogger(Swagger2MarkupTest.class);
#Autowired
private MockMvc mockMvc;
#Test
public void createSpringfoxSwaggerJson() throws Exception {
//String designFirstSwaggerLocation = Swagger2MarkupTest.class.getResource("/swagger.yaml").getPath();
String outputDir = System.getProperty("io.springfox.staticdocs.outputDir");
MvcResult mvcResult = this.mockMvc.perform(get("/v2/api-docs")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andReturn();
MockHttpServletResponse response = mvcResult.getResponse();
String swaggerJson = response.getContentAsString();
Files.createDirectories(Paths.get(outputDir));
try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputDir, "swagger.json"), StandardCharsets.UTF_8)){
writer.write(swaggerJson);
}
}
}
Failed to load Application Context and could not be able to load properties file which is in classpath
Anyone please help me??

Categories