I have the following servlet code:
SearchResult[] basicResults = AuctionSearchClient.basicSearch(search, numToSkip, numToReturn);
request.setAttribute("search_result", basicResults);
request.getRequestDispatcher("/search.jsp").forward(request, response);
Then in my search.jsp file I have the following code:
SearchResult[] searchResult = (SearchResult[])request.getAttribute("search_result");
However I am getting an error saying:
SearchResult cannot be resolved to a type
request is an object of type HttpServletRequest.
Why am I getting this casting error?
Related
{"error":"OK","langId":1,
"langName":"C++",
"langVersion":"5.1.1",
"time":0,
"date":"2017-04-03 15:38:19",
"status":0,
"result":11,
"memory":0,
"signal":0,"public":false,
"source":"","output_encoded":"",
"output_type":"text","output":"",
"stderr":"",
"cmpinfo":"\/usr\/lib\/gcc\/x86_64-linux-gnu\/6\/..\/..\/..\/x86_64-linux-gnu\/Scrt1.o: In function `_start':\n(.text+0x20): undefined reference to `main'\ncollect2: error: ld returned 1 exit status\n"
}
I am getting an error, I am unable to figure out where I am going wrong?
API Call :
public interface SubmitCodeService {
#Headers("Content-Type: application/json")
#POST("/api/v3/submissions")
Call<IdResponse> postCode(#Body JSONObject code, #Query("access_token") String accessToken );
#GET("/api/v3/submissions/{id}")
Call<CodeOutputResponse> getOutput(
#Path("id") Integer submissionId,
#Query("access_token") String accessToken,
#Query("withOutput") boolean withOutput,
#Query("withSource") boolean withSource,
#Query("withStderr") boolean withStderr,
#Query("withCmpinfo") boolean withCmpinfo);
}
I am submitting a simple HelloWorld program, I am getting an id back in response, however when I try to get the output, it throws this error.
Thanks in advance for your help.
Update : I am able to get it up and running by modifying the code to this :
Call<IdResponse> postCode(#Body HashMap<String,String> code, #Query("access_token") String accessToken );
"source":""
It seems that your postCode function is not correctly sending the source code. This means no main function is defined which causes the error mentioned in your post.
You need to review how you construct the value passed to code in postCode to see if it matches what the API expects.
I got a java.lang.AssertionError when I was attempting to verify the href. The response body looks fine,
MockHttpServletResponse:
Status = 200
Error message = null
Headers = {Content-Type=[application/json;charset=UTF-8]}
Content type = application/json;charset=UTF-8
Body = {"itemName":"ThinkPad","links":[{"rel":"self","href":"http://localhost/items/001"}]}
Forwarded URL = null
Redirected URL = null
Cookies = []
but when called this sentence: andExpect(jsonPath("$.links[0].href", hasItem(endsWith("/items/001"))))
The error occured:
java.lang.AssertionError: JSON path "$.links[0].href"
Expected: a collection containing ""
but: was "http://localhost/items/001"
at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
at org.springframework.test.util.JsonPathExpectationsHelper.assertValue(JsonPathExpectationsHelper.java:74)
at org.springframework.test.web.servlet.result.JsonPathResultMatchers$1.match(JsonPathResultMatchers.java:86)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:171)
at scnz.api.controller.ItemDispatchControllerTest.getCurrentStock(ItemDispatchControllerTest.java:62)
Here is the test code:
#Test
public void getCurrentStock() throws Exception {
Item item = new Item("001", "ThinkPad");
when(service.retrieve("001")).thenReturn(item);
mockMvc.perform(get("/items/001"))
.andDo(print())
.andExpect(jsonPath("$.itemName", is(item.getItemName())))
.andExpect(jsonPath("$.links[0].href", hasItem(endsWith("/items/001"))))
.andExpect(status().isOk());
Can anyone figure out where is wrong?
The actual result of jsonPath(...) for "$.links[0].href" is just a String as stated in the AssertionError.
The expected result for hasItem(...) is a collection as stated in the AssertionError.
In your case therefore just use endsWith(...) withouch hasItem(...). If your expression for jsonPath(...) returns a collection (e.g. via "$.links[*].href") instead of a single item you should use hasItem(...).
I have following code in my servlet
PrintWriter out = response.getWriter();
out.println("Getting Context scoped attributes<br>");
ServletContext sc = getServletConfig().getServletContext();
Enumeration contextAttribNames = sc.getAttributeNames();
while(contextAttribNames.hasMoreElements()){
String attribName = (String) contextAttribNames.nextElement();
String attribValue = (String) sc.getAttribute(attribName);//Line#21
out.println("<b>" + attribName + ":</b> " + attribValue + "<br>");
}
It just tries to get all the attributes associated with application/context scope and print their values.
The code compiles fine, but fails when I invoke this servlet from an url pattern
Following is the error I get
"HTTP Status 500 - org.apache.catalina.core.DefaultInstanceManager cannot be cast to java.lang.String"
java.lang.ClassCastException: org.apache.catalina.core.DefaultInstanceManager cannot be cast to java.lang.String
com.servlet.scopes.GetContextScopeServlet.doGet(GetContextScopeServlet.java:21)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
As per the documentation, javax.servlet.ServletContext has a method to get attribute with following signature
public Object getAttribute(String attribName)
and this is the reason why I'm casting to String at Line#21
Please help me in understanding the problem and resolving the issue...
Env Details :
OS - Windows7
Server - Apache Tomcat 7.x
JavaEE-6 specification
Attributes are not necessarily all of type String. They can be any object type. But you're trying to use them all as String objects
String attribValue = (String) sc.getAttribute(attribName);//Line#21
You don't know their type, so you can just do
Object attribValue = sc.getAttribute(attribName);//Line#21
The attributes in a ServletContext aren't always String objects; they can be anything, and are often such items as database pools. You should almost never cast an object to String; instead, properly parameterize your Enumeration as Enumeration<String>, and either use toString() on the attribute values or just use the bare Object in your string concatenation to have the compiler call toString() implicitly.
I am trying to make a call to my REST Service using Object Mapper.
url = new URL("http://phx5qa01c-8539.host.com:8080/bservice/BService/v1/getSimpleString");
String str = mapper.readValue(url, String.class);
And that url will give me this String back-
{ attributes : [ { nm : "SELLERS2" vt : "java.util.Map" status :
"SUCCESS" jsonValue :
"{"lv":[{"v":{"regSiteId":null,"userState":null,"userId":609},"cn":1}],"lmd":20130206211109}"
} ]}
When I am trying that URL on the browser, I am getting back the above String. But as soon as I do the same thing in the code. I am getting this Exception below-
org.codehaus.jackson.map.JsonMappingException: Can not deserialize
instance of java.lang.String out of START_OBJECT token
Can anyone help me with this why I am getting this exception below.
Jackson is trying to deserialize your json as a new string object but the properties dont match up e.g. it cant find a method String.setAttributes(). The 'out of START_OBJECT token' is a catch-all for any deserialisation errors, there may be more info further down the stack trace.
Try:
Map myMap = mapper.readValue(url, Map.class);
Or if you really want the string, don't use Jackson just read the url to a string using standard java code or commons-io:
String str = IOUtils.toString(url);
I am getting the following warning in Netbeans:
incompatible types
found : carPackage.port.search
required : carPackage.SearchResponse
In my JSP page, I have the following code:
CarService service = new CarService();
CarPort port = service.getCarPort();
SearchResponse searchResult = port.search("Toyota");
The error obviously occurs on this line:
SearchResponse searchResult = port.search("Toyota");
What datatype should I put in instead of SearchResponse?
Thanks,
Lucas
You're missing ; from the end. If CarPort.search returns SearchResponse, then your datatypes are correct.