I am new to building web applications using spark java.
I am trying to use 'Before' filter but getting the below error. please help. I have pasted my code below.Bootstrap is my class having the main method.
Error: "The method before is undefined for the type BootStrap"
public class BootStrap {
public static void main(String[] args) throws Exception {
ipAddress("localhost");
port(3003);
staticFileLocation("/public/html");
before((request, response) -> {
String user = request.queryParams("user");
String password = request.queryParams("password");
String dbPassword = usernamePasswords.get(user);
if (!(password != null && password.equals(dbPassword))) {
halt(401, "You are not welcome here!!!");
}
});
}
I think it's just lacking to statically import Spark.*;
Not sure this helps, but according to this "Access-Control-Request-Method" is a request header, not a response header. That said, a 404 always shows that the resource you want to find does not exist. Are you sure your url is correct?
Related
I have a JAVA Class that is defied as a managed-bean. The code below is a stripped down version of it:
package ca.wfsystems.core;
import lotus.domino.*;
public class Utils {
public static void recycleObjects(Object... args) {
for (Object o : args) {
if (o != null) {
if (o instanceof Base) {
try {
((Base) o).recycle();
} catch (Throwable t) {
// who cares?
}
}
}
}
} //end recycleObjects
public static void sysOut(Object msg){
System.out.println(msg.toString());
} //end sysOut
}// End Class
The call to recycleObjects(someObject) works fine when called from JAVA Code, but when I call it from SSJS in a button on an XPage called TestError I get the message "State data not available for /TestError because no control tree was found in the cache."
The SSJS code in the button is:
WFSUtils().sysOut("In Button");
var vw:NotesView = WFSAppProperties().get(sessionScope.get("ssApplication")).getAppDB().getView("vwWFSForms");
WFSUtils().sysOut("Testing Bean" + vw.getName());
WFSUtils().recycleObjects(vw);
where WFSUtils is the name of the managed bean.
the error in the client says:
Error while executing JavaScript action expression
Script interpreter error, line=6, col=12: Java method 'recycleObjects(lotus.domino.local.View)' on java class 'ca.wfsystems.core.Utils' not found
JavaScript code
I have searched for the error "State data not available for" but found a single reference aout it when using the Extension Library but this code does not use it.
You are using varargs in your method.
It's not possible to use varargs from SSJS. Instead, you might call the same method as:
WFSUtils().recycleObjects([vw]);
It will work in that way.
I am developing a struts2 application (Struts 2.3.14, java 1.7, on a Tomee plus 1.5.1 server).
I have a bunch of "detail" actions, and all of them contain the following code:
private Long modelId;
public Long getModelId() {
return modelId;
}
public void setModelId(Long modelId) throws Exception {
this.modelId = modelId;
(...some other stuff...)
}
In every action I also have a "persist" action that I use to save data, like this one:
#Action(value = "persistEntity", results = {
#Result(name = "success", location = "entityDetail",
type = "redirectAction", params = {"modelId", "%{modelId}"})
})
public String persist() throws Exception {
this.modelId = [save method invocation]
return "success";
}
After saving I try to redirect the user back to the detail page, but I get the following error:
Unexpected Exception caught setting 'modelId' on 'class classpath.DetailAction':
Error setting expression 'modelId' with value '[Ljava.lang.String;#43b5d2fe'
So, it seesm like Struts is handling my masterId as a String array... I had a look at this question, but it was no help for me.
What is most strange to me, after I get this error I get the same error every time I try to enter an existing entity, but if I restart my application I can enter existing entities without any error.
Thank you!
Well, turns out I was misleaded by Struts2 error message... The framework was correctly trying to set the parameter in my action, but I had an exception thrown by the
(...some other stuff...)
section. I went through the whole log file, and finally found the real issue.
Thank you anyway.
I'm trying to run this functional test
public class JsonRenderTest extends FunctionalTest {
#Before
public void setup() {
Fixtures.deleteDatabase();
Fixtures.loadModels("data.yml");
}
#Test
public void testThatJsonRenderingWorks() {
Response response = GET("/recipe/1");
assertIsOk(response);
}
}
The action answering this call is this
public static void showRecipe(Long id){
Recipe recipe = Recipe.findById(id);
notFoundIfNull(recipe);
renderJSON(recipe);
}
When I run the test in firefox using the TestRunner at http://localhost:8080/#tests
I get this error message:
Failure, Response status expected:<200> but was:<404>
Now if I run this url http://localhost:8080/recipe/1 in a browser, I get the json responce I'm expecting wich is a json representation of my recipe object.
There is of course a recipe in the database with id 1.
Now here is my question. Why is the test failing when the browser is not. I tryed this in Chrome, IE and FF with the same result.
Any pointers would be much appreciated.
Thanks
-Alain
Thanks eveyone.
Ok I found the answer.
It appears that my test was running before the fixture data was fully loaded.
I was running my tests against a local MySql database.
When I removed the call
Fixtures.deleteDatabase();
The test was running fine.
To fix the problem I am now running my test against a mem database with this in the application.conf file
%test.db.url=jdbc:h2:mem:play;MODE=MYSQL;LOCK_MODE=0
You can use a helper method to add content type to your request
public Request jsonRequest(Request request) {
request.contentType = "application/json";
request.format = "json";
return request;
}
Then your test become
#Test
public void testThatJsonRenderingWorks() {
Response response = GET(jsonRequest(newRequest)), "/recipe/1");
assertIsOk(response);
}
}
You can also you WS classes to do real http tests insted.
Our application uses several back-end services and we maintain wrappers which contain the methods to make the actual service calls. If any exception occurs in any of those methods while invoking a service, we throw a custom exception encapsulating the original exception as shown below.
interface IServiceA {
public void submit(String user, String attributes);
}
public class ServiceAWrapper implements IserviceA {
private ActualService getActualService() {
.....
}
public void submit(String user, String attributes) {
try {
Request request = new Request();
request.setUser(user);
request.setAttributes(attributes);
getActualService().call(request);
} catch(ServiceException1 e) {
throw new MyException(e, reason1);
} catch(ServiceException2 e) {
throw new MyException(e, reason2);
}
}
}
I would like to know if there's any framework that would allow me to
capture (and probably log) all the
parameters passed to my wrapper
methods at run-time; if the methods
are called.
capture the actual exception
object(MyException instance in above
example), if any thrown; so that I
could append the passed parameters
to the object at run-time.
I am currently exploring AspectJ to see if it can address my requirements, but I am not sure if it can be used to capture the parameters passed to methods at runtime and also to capture exception objects, if any occur.
Thanks.
With AspectJ, you can use around advice to execute advice instead of the code at the join point. You can then execute the actual join-point from within the advice by calling proceed. This would allow you to capture the input parameters, log them, and proceed to call the actual method.
Within the same advice you could capture any logs throw from the method, and inspect or log them before passing it back up to higher levels.
Matt B's answer is right. Specifically, you can do something like this:
aspect MonitorServiceCalls {
private final Logger LOG = LoggerFactory.getLog("ServiceCallLog");
Object around() throws MyException: call(public * *(..) throws MyException)
&& target(IServiceA+) {
MethodSignature msig = (MethodSignature)thisJoinPoint;
String fullMethName = msig.getMethod().toString();
try {
Object result = proceed();
LOG.info("Successful call to {} with arguments {}",
fullMethName,
thisJoinPoint.getArgs());
return result;
} catch(MyException e) {
LOG.warn("MyException thrown from {}: {}", msig.getMethod(), e);
throw e;
}
}
}
AspectJ is the right option. You will be able to get hold of the parameters by way of a JoinPoint object that will be passed to your advise methods. You can also get hold of the exception either by implementing an after throwing advise or an around advise.
I want to generate a client program using the service
I am unable to display the results, how can I do so?
import java.rmi.RemoteException;
public class searchtry {
public static void main(String[] args) throws RemoteException {
SearchRequest request=new SearchRequest();
SearchRequestType1 type1=new SearchRequestType1();
query.setAppId("*********************************"); //Windows Live gave this id for using that service
query.setSources(new SourceType[]{SourceType.Web});
query.setQuery("Java");
aratip.setParameters(request);
SearchResponseType0 answer= client.search(type1);
System.out.println(answer.toString());
}
For starters, calling
answer.toString();
May or may not result in anything (usually won't). You might just get a string that represents the instance, not the string you're expecting. You need to find a method on SearchResponseType0 that will give you the string representation of the response. Perhaps a method like getContent() or getResponse() or something like that but without understanding more about the web service it's difficult to give you more help. Bottom line, you're using the wrong method to attempt to get the string content of the result.
It looks like your are using the bing-search-java-sdk. They have a very nice example on their homepage you might want to look at:
BingSearchServiceClientFactory factory = BingSearchServiceClientFactory.newInstance();
BingSearchClient client = factory.createBingSearchClient();
SearchRequestBuilder builder = client.newSearchRequestBuilder();
builder.withAppId(applicationId);
builder.withQuery("msdn blogs");
builder.withSourceType(SourceType.WEB);
builder.withVersion("2.0");
builder.withMarket("en-us");
builder.withAdultOption(AdultOption.MODERATE);
builder.withSearchOption(SearchOption.ENABLE_HIGHLIGHTING);
builder.withWebRequestCount(10L);
builder.withWebRequestOffset(0L);
builder.withWebRequestSearchOption(WebSearchOption.DISABLE_HOST_COLLAPSING);
builder.withWebRequestSearchOption(WebSearchOption.DISABLE_QUERY_ALTERATIONS);
SearchResponse response = client.search(builder.getResult());
for (WebResult result : response.getWeb().getResults()) {
System.out.println(result.getTitle());
System.out.println(result.getDescription());
System.out.println(result.getUrl());
System.out.println(result.getDateTime());
}