package com.cadrlife.devsearch.esplugin;
import com.cadrlife.devsearch.esplugin.service.ShowResource;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.base.Strings;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.rest.*;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestStatus.OK;
public class ShowRestHandler extends BaseRestHandler {
private final ShowResource showResource;
private final ObjectMapper objectMapper;
@Inject
public ShowRestHandler(Settings settings, Client client, RestController restController, ShowResource showResource, ObjectMapper objectMapper) {
super(settings, client);
this.showResource = showResource;
this.objectMapper = objectMapper;
restController.registerHandler(GET, "/_dev-search/showDoc", this);
restController.registerHandler(GET, "/_dev-search/showProject", this);
}
@Override
public void handleRequest(final RestRequest request, final RestChannel channel) {
String repo = request.param("repo");
String project = request.param("project");
String path = request.param("path");
if (Strings.isNullOrEmpty(repo)) {
channel.sendResponse(new BytesRestResponse(RestStatus.BAD_REQUEST, "Parameter repo required"));
} else if (Strings.isNullOrEmpty(project)) {
channel.sendResponse(new BytesRestResponse(RestStatus.BAD_REQUEST, "Parameter project required"));
} else {
try {
channel.sendResponse(new BytesRestResponse(OK, objectMapper.writeValueAsString(showResource.get(repo, project, path))));
} catch (Exception e) {
logger.error("Failed for '{}', '{}', '{}'", e, repo, project, path);
channel.sendResponse(new BytesRestResponse(RestStatus.INTERNAL_SERVER_ERROR, e.getMessage()));
}
}
}
}