So I'm tying to develop a very simple TeamCity Plugin. The Plugin is just suppose to take user input and display it. My code seems to work on my local Tomcat server but when i try to integrate it into TeamCity via the Basecontroller class from jetbrains there seems to be no output. This is my code
public class AppServer extends BaseController{
private PluginDescriptor myDescriptor;
public AppServer (WebControllerManager manager, PluginDescriptor descriptor) {
manager.registerController("/demoPlugin.html",this);
myDescriptor=descriptor;
}
public void doGet(HttpServletRequest request, HttpServletResponse responseone)throws IOException, ServletException {
try {
responseone.setContentType("text/html; charset=UTF-8");
PrintWriter out = responseone.getWriter();
try {
out.println("<!DOCTYPE html>");
out.println("<html><head>");
out.println("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>");
out.println("<title>Echo Servlet</title></head>");
out.println("<body><h2>You have enter</h2>");
String requirement = request.getParameter("requirement");
if (requirement == null || (requirement = htmlFilter(requirement.trim())).length() == 0) {
out.println("<p>Agent Requirement: Not specified</p>");
}
else {
out.println("<p>Agent Requirement: " + requirement + "</p>");
}
out.println("<a href='form_input.html'>BACK</a>");
out.println("</body></html>");
}
finally{
out.close();
}
}
finally{
return;
}
}
public void doPost(HttpServletRequest request, HttpServletResponse responseone)
throws IOException, ServletException {
doGet(request, responseone);
}
private static String htmlFilter(String message) {
if (message == null) return null;
int len = message.length();
StringBuffer result = new StringBuffer(len + 20);
char aChar;
for (int i = 0; i < len; ++i) {
aChar = message.charAt(i);
switch (aChar) {
case '<': result.append("<"); break;
case '>': result.append(">"); break;
case '&': result.append("&"); break;
case '"': result.append("""); break;
default: result.append(aChar);
}
}
return (result.toString());
}
protected ModelAndView doHandle(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse) throws Exception {
return new ModelAndView(myDescriptor.getPluginResourcesPath("Hello.jsp"));
}
}
I honestly don't know what I'm doing and I cannot seem to find any good tutorials regarding Basecontroller class from jetbrains. Please help.
Related
I have the following POST servlet that adds new node under certain resource with parameters(name and last nam) from the request:
#Component(
service = Servlet.class,
property = {
"sling.servlet.paths=/bin/createuser",
"sling.servlet.methods=" + HttpConstants.METHOD_POST
})
public class CreateNodeServlet extends SlingAllMethodsServlet {
/**
* Logger
*/
private static final Logger log = LoggerFactory.getLogger(CreateNodeServlet.class);
#Override
protected void doPost(final SlingHttpServletRequest req, final SlingHttpServletResponse resp) throws IOException {
log.info("Inside CreateNodeServlet");
ResourceResolver resourceResolver = req.getResourceResolver();
final Resource resource = resourceResolver.getResource("/content/test/us/en");
String name = req.getParameter("name");
String lastname = req.getParameter("lastname");
log.info("name :{}",name);
log.info("lastname :{}",lastname);
Node node = resource.adaptTo(Node.class);
try {
log.info("Node {}", node.getName() );
Node newNode = node.addNode(name+lastname, "nt:unstructured");
newNode.setProperty("name", name);
newNode.setProperty("lastname", lastname);
resourceResolver.commit();
} catch (RepositoryException e) {
e.printStackTrace();
} catch (PersistenceException e) {
e.printStackTrace();
}
resp.setStatus(200);
resp.getWriter().write("Simple Post Test");
}
}
I tried creating unit test for this I got this so far:
#ExtendWith(AemContextExtension.class)
class CreateNodeServletTest {
private final AemContext context = new AemContext();
private CreateNodeServlet createNodeServlet = new CreateNodeServlet();
#Test
void doPost() throws IOException, JSONException {
context.currentPage(context.pageManager().getPage("/bin/createuser"));
context.currentResource(context.resourceResolver().getResource("/bin/createuser"));
context.requestPathInfo().setResourcePath("/bin/createuser");
MockSlingHttpServletRequest request = context.request();
MockSlingHttpServletResponse response = context.response();
createNodeServlet.doPost(request, response);
JSONArray output = new JSONArray(context.response().getOutputAsString());
assertEquals("Simple Post Test", output);
}
}
however this is not working I am getting null pointer on this line
Node node = resource.adaptTo(Node.class);
can some one help what I am missing and some tips will be of great help as I am new to AEM, and there is not much resources about unit testing sling servlets ?
I think you need to register JCR_MOCK as resource resolver type
new AemContext(ResourceResolverType.JCR_MOCK);
I am an Android developer, I am working with Retrofit. The first day I had a response but the second day the response did not come, why I will working after I can uninstall and install the app then only it will work why, how to I resolve it please help me...
private void HomeWorks() {
HomeWorkApi homeWorkApi =
MissReportServer.getClient().create(HomeWorkApi.class);
Call<VrrittamResponse<ArrayList<HomeWork>>> call =
homeWorkApi.getHomeWork(access_token);
call.enqueue(new Callback<VrrittamResponse<ArrayList<HomeWork>>>() {
#Override
public void onResponse(Call<VrrittamResponse<ArrayList<HomeWork>>> call, Response<VrrittamResponse<ArrayList<HomeWork>>> response) {
try {
ArrayList<HomeWork> homeWork = response.body().getContent();
if (homeWork != null && !homeWork.isEmpty()) {
recyclerView.setAdapter(new HomeWorkAdapter(homeWork,
R.layout.list_item_homework, getActivity()));
}
else {
ExceptionHandle.alertDialogNotShow(getActivity());
}
}
catch (Exception ex){
ExceptionHandle.alertDialogNotShow(getActivity());
}
}
#Override
public void onFailure(Call<VrrittamResponse<ArrayList<HomeWork>>> call, Throwable t) {
Log.e("TAG",t.getMessage());
ExceptionHandle.alertDialogShow(getActivity());
}
});
}
I want to read a list of url to the same site which support http 1.1 keep-live.
I try to use netty to do this and it works.
but when i get the response,i can not identify it is for which url.
how can i get the request url from method messageReceived below:
public static void main(String[] args) throws InterruptedException, URISyntaxException {
String host = "localhost";
int port = 8080;
String[] paths = new String[]{"1.html", "2.html", "3.html"};
EventLoopGroup group = new NioEventLoopGroup();
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
#Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast(new HttpClientCodec());
p.addLast(new HttpContentDecompressor());
p.addLast(new SimpleChannelInboundHandler<HttpObject>() {
#Override
protected void messageReceived(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
if (msg instanceof HttpContent) {
HttpContent content = (HttpContent) msg;
System.out.println("response from url ?:" + content.content().toString());
}
}
});
}
});
Channel ch = b.connect(host, port).sync().channel();
for (String path : paths) {
HttpRequest request = new DefaultFullHttpRequest(
HttpVersion.HTTP_1_1, HttpMethod.GET, path);
request.headers().set(HttpHeaderNames.HOST, host);
request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
request.headers().set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
ch.writeAndFlush(request);
}
Try this:
p.addLast(new SimpleChannelInboundHandler<Object>() {
#Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
if (msg instanceof HttpRequest) {
System.out.println("I'm HttpRequest");
FullHttpRequest req = (FullHttpRequest) msg;
if (HttpHeaders.is100ContinueExpected(req)) {
ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
}
System.out.println("response from url ?:" + req.getUri());
ByteBuf content = req.content();
}
}
});
Don't know what version of netty are you using. If 5.0+, rename channelRead to messageReceived.
To use push method , we use the famous JS object EventSource :
This is the client part which is easy to develop it :
var eventSource = new EventSource("controller/action");
eventSource.onmessage = function(event) {
document.getElementById('foo').innerHTML = event.data;
};
However , i get difficulty to configure push method in server part(Grails) .
When , i peek in JEE app developped by Servlets , i can see that the server part is as following :
http://viralpatel.net/blogs/html5-server-sent-events-java-servlets-example/
public class TestServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//content type must be set to text/event-stream
response.setContentType("text/event-stream");
//encoding must be set to UTF-8
response.setCharacterEncoding("UTF-8");
PrintWriter writer = response.getWriter();
for(int i=0; i<10; i++) {
writer.write("data: "+ System.currentTimeMillis() +"\n\n");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
writer.close();
}
}
To convert this servlet to action controller :
def push(){
render(contentType:'text/event-stream',characterEncoding:'UTF-8'){
[dt:"data: "+ System.currentTimeMillis() +"\n\n"]
}
}
and in client part :
var eventSource = new EventSource(baseURL+"external/push");
eventSource.onmessage=function(e){
console.log(e.data.dt);
}
Unfortunately, i don't get any result at console .
I'm not sure if the render method will handle 'text/event-stream' correctly, but you have direct access to the response object in the action:
def push() {
//content type must be set to text/event-stream
response.setContentType("text/event-stream");
//encoding must be set to UTF-8
response.setCharacterEncoding("UTF-8");
for(int i=0; i<10; i++) {
response.outputStream.write("data: "+ System.currentTimeMillis() +"\n\n");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
response.outputStream.flush()
}
def push = {
response.setContentType("text/event-stream");
for(def i=0;i<10;i++) {
render("data $i: ${System.currentTimeMillis()}\n");
sleep(1000)
}
}
I'm trying to access a XML file from client side in GWT. But it looks like the sendRequest method is not getting fired at all.
I'm able to see the xml in the browser. Do I need to do any thing in the server side?
Any help is appreciated.
Here's my code
String xmlurl = "http://localhost:8888/test.xml";
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(xmlurl));
try {
Request request = builder.sendRequest(null, new RequestCallback() {
public void onError(Request request, Throwable exception) {
System.out.println(exception);
}
public void onResponseReceived(Request request, Response response) {
if (200 == response.getStatusCode()) {
System.out.println(response.getText());
} else {
System.out.println(response.getStatusCode());
}
}
});
} catch (RequestException e) {
System.out.println("exception"+e);
}
I tried the following code too, but have the same problem. The developer tool shows response status as 200 and correct response text. Only, its not working in the code.
String xmlurl = "http://127.0.0.1:8888/test.xml";
httpGetFile(xmlurl, new AsyncCallback<String>() {
public void onFailure(Throwable caught) {
xmlData = "Error";
}
public void onSuccess(String xmlText) {
xmlData = xmlText;
}
});
public static void httpGetFile(final String url, final AsyncCallback<String> callback) {
final RequestBuilder rb = new RequestBuilder(RequestBuilder.GET, url);
rb.setCallback(new RequestCallback() {
public void onResponseReceived(Request request, Response response) {
try {
System.out.println("dafadfdf");
final int responseCode = response.getStatusCode() / 100;
if (url.startsWith("file:/") || (responseCode == 2)) {
callback.onSuccess(response.getText());
} else {
callback.onFailure(new IllegalStateException("HttpError#" + response.getStatusCode() + " - " + response.getStatusText()));
}
} catch (Throwable e) {
callback.onFailure(e);
}
}
public void onError(Request request, Throwable exception) {
callback.onFailure(exception);
}
});
try {
rb.send();
} catch (RequestException e) {
callback.onFailure(e);
}
}
Always Use logging instead of System.out.print statements https://developers.google.com/web-toolkit/doc/latest/DevGuideLogging
Step 1 - Add logging statements to failure, success and try catch statements. Clean up the exception.
Step 2 - "Parsing the XML" should be done inside the "onSuccess" method of the rb callback.
You do not need a RequestBuilder at all to access an XML file. You can use an ExternalTextResource for this:
https://developers.google.com/web-toolkit/doc/latest/DevGuideClientBundle#TextResource