ResponseBody cannot be resolved to a type - model-view-controller

I'm trying to write this method in my controller:
#ResponseBody
#RequestMapping(value = {"/getTeams"}, method = RequestMethod.GET)
public void getMaxRequestSize(HttpServletResponse response) {
String autoCompleteList = null;
List<Team> teams = atService.getAllTeams();
Iterator itr = teams.iterator();
while (itr.hasNext()) {
autoCompleteList += itr.next().toString() + "\n";
}
response.setContentType("text/html");
PrintWriter writer;
try {
writer = response.getWriter();
writer.write(autoCompleteList);
} catch (IOException e) {
e.printStackTrace();
}
}
For some reason I always get an error on the ResponseBody annotation (= cannot be resolved to a type). I googled for quite a while and didn't find a solution. I'm sure it's something silly. I can use all the other annotations without any problems...

Is this a Maven project? You might be ending up with the old Spring 2.5.6 jars in your war file instead of Spring 3. Eclipse's POM editor's Dependency Hierarchy tab can help you figure out if that's the case.

Related

How to fix issue RestControllerAdivse not working?

I have an issue related to RestControllerAdvice.
I have built an internal jar file as my own library and I implement some exception handler.
Anyway, that RestControllerAdvice is not working when have throw exception error.
RestControllerAdvice
#RestControllerAdvice
public class ApiControllerHandler {
#ExceptionHandler(ApiException.class)
public #ResponseBody
ApiResponse handleApiRequestException(ApiException e) {
ApiResponse response = new ApiResponse();
response.setCode(e.response.getCode());
response.setMessage(e.response.getMessage());
return response;
}
}
validator method
public static void request(JSONObject jsonReq, String requestKey) throws ApiException{
if (requestKey.isEmpty()) {
throw new ApiException("01", "Please input request validate key");
}
String key = jsonReq.getString(requestKey);
if (StringUtils.isEmpty(key)) {
throw new ApiException("01", requestKey + " Can not be null or empty.");
}
}
RestController
#PostMapping("/")
public String index(#RequestBody Map<String, Object> map){
JSONObject jsonObject = new JSONObject(map);
SPNValidator.request(jsonObject, "username");
return "Hello";
}
Request
{
"username" : ""
When post this request, exception will be throw because I already handled request not empty nor null
but my restControlleradvise is not working, it throws internal exception error.
Note: it works as normal if i use the same project,
but when build as jar file for other use, this function not work.
thanks.
One of the possible reason
When you build as internal JAR at that time spring dosen't know about any class in JAR so it will not search any package/Class from jar file so that's why your #RestControllerAdvice from internal JAR is not working
To solve this please use your internal JAR pacakge name in #ComponentScan
like below
#ComponentScan(basePackages = {"com.exception.base"})
so spring will inlcude ApiControllerHandler while scanning you project file.

Reading property file in Spring MVC app

I'm trying to read a property file using below code, basically I'm having a Spring Boot app and I'm trying to read the below non spring bean class.The property file is in src/main/resource directory.
public class VisaProperties {
static Properties properties;
static {
try {
properties = new Properties();
String propertiesFile = System.getProperty("ftproperties");
if (propertiesFile == null) {
properties.load(VisaProperties.class.getResourceAsStream("motoconfig.cybersource.properties"));
} else {
properties.load(new FileReader(propertiesFile));
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static String getProperty(Property property) {
return (String) properties.get(property.getValue());
}
}
and trying call the end point property using below code getting null. How can I call the property?
VisaProperties.getProperty(Property.END_POINT)
You can simplify the code as:
final Properties properties = new Properties();
try (final InputStream stream =
this.getClass().getResourceAsStream("config.properties")) {
properties.load(stream);
}
Note: Use "try with resources" so that stream will be automatically
closed when the try {} block exits.
Done, using the code below:
Properties properties = new Properties();
InputStream inputStream = VisaProperties.class
.getClassLoader()
.getResourceAsStream("config.properties");
properties.load(inputStream);
inputStream.close();

How to download data from url?

I can download data via HttpUrlConnection and InputStream but I need to download raw-data. So, i want to create a DownloadManager via raw-data, then using raw-data I convert this data to binary or image format. According to my research, I see "download file from url" but I can't download file in mac? Always, I get FileNotFoundException. Please help me. How I can download data from url?
public class DownloadData extends AsyncTask<Void,Void,Void> {
#Override
protected Void doInBackground(Void... params) {
try {
downloadData("https://blablalabla/get");
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public void downloadData(String myurl) throws IOException {
URL u = new URL(myurl);
InputStream is = u.openStream();
DataInputStream dis = new DataInputStream(is);
byte[] buffer = new byte[1024];
int length;
OutputStream fos = new FileOutputStream(new File(Environment.getExternalStorageDirectory() + "/Users/ilknurpc/Desktop/text.docx"));
while ((length = dis.read(buffer))>0) {
fos.write(buffer, 0, length);
}
}
}
If you want to construct a workable download manager, I would suggest that you take a look at the
Tomcat Default Servlet Implementation
.
There a few number of HTTP headers that you need to understand such as E-Tags and Http Range Headers for a proper implementation.
Thankfully the Tomcat Default Servlet handles the prerequisites for you.
You can adapt this servlet in your code with minor changes (package declaration etc).

Test case using SpringJunitRunner

I want to write junit test case for the below code with springJunitRunner.
the below piece of code is one service in a class.
#Component
#Path(/techStack)
public class TechStackResource {
#Autowired
private transient TechStackService techStackService;
#GET
#Path("/{id}")
#Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Response getTechStackById(final #PathParam("id") Integer technicalstackid) {
final TechStackResponse response = new TechStackResponse();
int statusCode = Constants.HTTP_STATUS_OK_200;
try {
TechStackModel techStackModel = techStackService.findObjectById(technicalstackid);
response.setGetTechStackDetails(GetTechStackDetails.newBuilder().technicalStack(techStackModel).build());
if (techStackModel == null) {
statusCode = Constants.HTTP_STATUS_ERROR_404;
}
} catch (EmptyResultDataAccessException erde) {
} catch (Exception e) {
LOGGER.error("Exception occured in TechStackResource.getTechStackById(technicalstackid) ", e);
throw new APMRestException(
"Exception while executing TechStackResource.getTechStackById(technicalstackid) ",
Constants.UNKNOW_ERROR, e);
}
return Response.status(statusCode).entity(response).build();
}
}
the configuration in web.xml for servlet is
<servlet-name>jersey-servlet</servlet-name>
<servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
Since you are using Jersey as well as Spring, you can use the SpringJunitRunner only to wire-up TechStackResource with its dependency TechStackService.
In order to test your REST handler method getTestStackById, you could go the POJO approach and invoke it directly. Alternatively, you can use Jersey's own MockWeb environment. To find out more about this, I recommend looking at the Jersey example sources, e.g. HelloWorld.

AfterThrowing advice not working Spring AOP

I cannot get my afterThrowing Spring AOP advice to fire,
I have made the point cut as generic as possible now and it still does not fire
I hope this is just a poor pointcut but I cannot see why, I would be grateful if anyone could see why
Advice
//Generic Exceptions
#AfterThrowing(value = "execution(* *(..)) throws Exception", throwing = "exception")
public void loggingGenericException(JoinPoint joinPoint, Exception exception) {
String classMethod = this.getClassMethod(joinPoint);
String stackTrace = "";
for (StackTraceElement element : exception.getStackTrace()) {
stackTrace += element.toString() + "\n";
}
String exceptionMessageAndStackTrace = exception.getMessage() + "\n" + stackTrace;
if (exception instanceof EmptyResultSetException) {
this.infoLevelLogging(joinPoint, classMethod);
} else {
this.errorLevelLogging(joinPoint, classMethod, exceptionMessageAndStackTrace);
}
}
Method that should be advised
public void getStudentTranscript(String studentId) throws RestClientException,IllegalArgumentException{
if (!this.serviceUrl.isEmpty()) {
if(studentId.isEmpty())
{
throw new IllegalArgumentException("studentId empty");
}
this.transcript = (Transcript) super.getForObject(this.serviceUrl,Transcript.class, studentId);
} else {
throw new IllegalArgumentException("url is empty");
}
}
If I run a test to check it is applied it is not working the test looks like this
#Test
public void testLoggingFiredOnExceptionInTranscriptRepository() throws Exception
{
Log log;
log = mock(Log.class);
when(log.isErrorEnabled()).thenReturn(true);
try {
loggingAspects.setLogger(log);
transcriptRepository.setServiceUrl("");
transcriptRepository.getStudentTranscript("12345");
} catch (RuntimeException e) {
System.out.println("e = " + e);
verify(log, times(1)).isErrorEnabled();
verify(log, times(1)).error(anyString());
}
}
The system out shows an exception fired
Can anyone offer any advice ( pun intended) :-)
Did you put the <aop:aspectj-autoproxy /> element in your spring configuration file? Otherwise, the AOP annotations won't be interpreted.
FYI, after having read your question, I created a sample project on my own and the #AfterThrowing annotation just works as it should.

Resources