use of com.google.gerrit.extensions.restapi.BinaryResult in project gerrit by GerritCodeReview.
the class RobotCommentsIT method twoFixesOfSameRobotCommentCanBeApplied.
@Test
public void twoFixesOfSameRobotCommentCanBeApplied() throws Exception {
assume().that(notesMigration.readChanges()).isTrue();
FixReplacementInfo fixReplacementInfo1 = new FixReplacementInfo();
fixReplacementInfo1.path = FILE_NAME;
fixReplacementInfo1.range = createRange(2, 0, 3, 0);
fixReplacementInfo1.replacement = "First modification\n";
FixSuggestionInfo fixSuggestionInfo1 = createFixSuggestionInfo(fixReplacementInfo1);
FixReplacementInfo fixReplacementInfo2 = new FixReplacementInfo();
fixReplacementInfo2.path = FILE_NAME;
fixReplacementInfo2.range = createRange(8, 0, 9, 0);
fixReplacementInfo2.replacement = "Some other modified content\n";
FixSuggestionInfo fixSuggestionInfo2 = createFixSuggestionInfo(fixReplacementInfo2);
withFixRobotCommentInput.fixSuggestions = ImmutableList.of(fixSuggestionInfo1, fixSuggestionInfo2);
addRobotComment(changeId, withFixRobotCommentInput);
List<RobotCommentInfo> robotCommentInfos = getRobotComments();
List<String> fixIds = getFixIds(robotCommentInfos);
gApi.changes().id(changeId).current().applyFix(fixIds.get(0));
gApi.changes().id(changeId).current().applyFix(fixIds.get(1));
Optional<BinaryResult> file = gApi.changes().id(changeId).edit().getFile(FILE_NAME);
BinaryResultSubject.assertThat(file).value().asString().isEqualTo("First line\nFirst modification\nThird line\nFourth line\nFifth line\nSixth line\n" + "Seventh line\nSome other modified content\nNinth line\nTenth line\n");
}
use of com.google.gerrit.extensions.restapi.BinaryResult in project gerrit by GerritCodeReview.
the class RobotCommentsIT method fixWithTwoCloseReplacementsOnSameFileCanBeApplied.
@Test
public void fixWithTwoCloseReplacementsOnSameFileCanBeApplied() throws Exception {
assume().that(notesMigration.readChanges()).isTrue();
FixReplacementInfo fixReplacementInfo1 = new FixReplacementInfo();
fixReplacementInfo1.path = FILE_NAME;
fixReplacementInfo1.range = createRange(2, 0, 3, 0);
fixReplacementInfo1.replacement = "First modification\n";
FixReplacementInfo fixReplacementInfo2 = new FixReplacementInfo();
fixReplacementInfo2.path = FILE_NAME;
fixReplacementInfo2.range = createRange(3, 0, 4, 0);
fixReplacementInfo2.replacement = "Some other modified content\n";
FixSuggestionInfo fixSuggestionInfo = createFixSuggestionInfo(fixReplacementInfo1, fixReplacementInfo2);
withFixRobotCommentInput.fixSuggestions = ImmutableList.of(fixSuggestionInfo);
addRobotComment(changeId, withFixRobotCommentInput);
List<RobotCommentInfo> robotCommentInfos = getRobotComments();
List<String> fixIds = getFixIds(robotCommentInfos);
String fixId = Iterables.getOnlyElement(fixIds);
gApi.changes().id(changeId).current().applyFix(fixId);
Optional<BinaryResult> file = gApi.changes().id(changeId).edit().getFile(FILE_NAME);
BinaryResultSubject.assertThat(file).value().asString().isEqualTo("First line\nFirst modification\nSome other modified content\nFourth line\nFifth line\n" + "Sixth line\nSeventh line\nEighth line\nNinth line\nTenth line\n");
}
use of com.google.gerrit.extensions.restapi.BinaryResult in project gerrit by GerritCodeReview.
the class AbstractSubmit method submitMultipleChangesOtherMergeConflictPreview.
@Test
public void submitMultipleChangesOtherMergeConflictPreview() throws Exception {
RevCommit initialHead = getRemoteHead();
PushOneCommit.Result change = createChange("Change 1", "a.txt", "content");
submit(change.getChangeId());
RevCommit headAfterFirstSubmit = getRemoteHead();
testRepo.reset(initialHead);
PushOneCommit.Result change2 = createChange("Change 2", "a.txt", "other content");
PushOneCommit.Result change3 = createChange("Change 3", "d", "d");
PushOneCommit.Result change4 = createChange("Change 4", "e", "e");
// change 2 is not approved, but we ignore labels
approve(change3.getChangeId());
try (BinaryResult request = submitPreview(change4.getChangeId())) {
assertThat(getSubmitType()).isEqualTo(SubmitType.CHERRY_PICK);
submit(change4.getChangeId());
} catch (RestApiException e) {
switch(getSubmitType()) {
case FAST_FORWARD_ONLY:
assertThat(e.getMessage()).isEqualTo("Failed to submit 3 changes due to the following problems:\n" + "Change " + change2.getChange().getId() + ": internal error: " + "change not processed by merge strategy\n" + "Change " + change3.getChange().getId() + ": internal error: " + "change not processed by merge strategy\n" + "Change " + change4.getChange().getId() + ": Project policy " + "requires all submissions to be a fast-forward. Please " + "rebase the change locally and upload again for review.");
break;
case REBASE_IF_NECESSARY:
case REBASE_ALWAYS:
String change2hash = change2.getChange().currentPatchSet().getRevision().get();
assertThat(e.getMessage()).isEqualTo("Cannot rebase " + change2hash + ": The change could " + "not be rebased due to a conflict during merge.");
break;
case MERGE_ALWAYS:
case MERGE_IF_NECESSARY:
assertThat(e.getMessage()).isEqualTo("Failed to submit 3 changes due to the following problems:\n" + "Change " + change2.getChange().getId() + ": Change could not be " + "merged due to a path conflict. Please rebase the change " + "locally and upload the rebased commit for review.\n" + "Change " + change3.getChange().getId() + ": Change could not be " + "merged due to a path conflict. Please rebase the change " + "locally and upload the rebased commit for review.\n" + "Change " + change4.getChange().getId() + ": Change could not be " + "merged due to a path conflict. Please rebase the change " + "locally and upload the rebased commit for review.");
break;
case CHERRY_PICK:
default:
fail("Should not reach here.");
break;
}
RevCommit headAfterSubmit = getRemoteHead();
assertThat(headAfterSubmit).isEqualTo(headAfterFirstSubmit);
assertRefUpdatedEvents(initialHead, headAfterFirstSubmit);
assertChangeMergedEvents(change.getChangeId(), headAfterFirstSubmit.name());
}
}
use of com.google.gerrit.extensions.restapi.BinaryResult in project gerrit by GerritCodeReview.
the class RestApiServlet method service.
@Override
protected final void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
final long startNanos = System.nanoTime();
long auditStartTs = TimeUtil.nowMs();
res.setHeader("Content-Disposition", "attachment");
res.setHeader("X-Content-Type-Options", "nosniff");
int status = SC_OK;
long responseBytes = -1;
Object result = null;
ListMultimap<String, String> params = MultimapBuilder.hashKeys().arrayListValues().build();
ListMultimap<String, String> config = MultimapBuilder.hashKeys().arrayListValues().build();
Object inputRequestBody = null;
RestResource rsrc = TopLevelResource.INSTANCE;
ViewData viewData = null;
try {
if (isCorsPreflight(req)) {
doCorsPreflight(req, res);
return;
}
checkCors(req, res);
checkUserSession(req);
ParameterParser.splitQueryString(req.getQueryString(), config, params);
List<IdString> path = splitPath(req);
RestCollection<RestResource, RestResource> rc = members.get();
globals.permissionBackend.user(globals.currentUser).checkAny(GlobalPermission.fromAnnotation(rc.getClass()));
viewData = new ViewData(null, null);
if (path.isEmpty()) {
if (rc instanceof NeedsParams) {
((NeedsParams) rc).setParams(params);
}
if (isRead(req)) {
viewData = new ViewData(null, rc.list());
} else if (rc instanceof AcceptsPost && "POST".equals(req.getMethod())) {
@SuppressWarnings("unchecked") AcceptsPost<RestResource> ac = (AcceptsPost<RestResource>) rc;
viewData = new ViewData(null, ac.post(rsrc));
} else {
throw new MethodNotAllowedException();
}
} else {
IdString id = path.remove(0);
try {
rsrc = rc.parse(rsrc, id);
if (path.isEmpty()) {
checkPreconditions(req);
}
} catch (ResourceNotFoundException e) {
if (rc instanceof AcceptsCreate && path.isEmpty() && ("POST".equals(req.getMethod()) || "PUT".equals(req.getMethod()))) {
@SuppressWarnings("unchecked") AcceptsCreate<RestResource> ac = (AcceptsCreate<RestResource>) rc;
viewData = new ViewData(null, ac.create(rsrc, id));
status = SC_CREATED;
} else {
throw e;
}
}
if (viewData.view == null) {
viewData = view(rsrc, rc, req.getMethod(), path);
}
}
checkRequiresCapability(viewData);
while (viewData.view instanceof RestCollection<?, ?>) {
@SuppressWarnings("unchecked") RestCollection<RestResource, RestResource> c = (RestCollection<RestResource, RestResource>) viewData.view;
if (path.isEmpty()) {
if (isRead(req)) {
viewData = new ViewData(null, c.list());
} else if (c instanceof AcceptsPost && "POST".equals(req.getMethod())) {
@SuppressWarnings("unchecked") AcceptsPost<RestResource> ac = (AcceptsPost<RestResource>) c;
viewData = new ViewData(null, ac.post(rsrc));
} else if (c instanceof AcceptsDelete && "DELETE".equals(req.getMethod())) {
@SuppressWarnings("unchecked") AcceptsDelete<RestResource> ac = (AcceptsDelete<RestResource>) c;
viewData = new ViewData(null, ac.delete(rsrc, null));
} else {
throw new MethodNotAllowedException();
}
break;
}
IdString id = path.remove(0);
try {
rsrc = c.parse(rsrc, id);
checkPreconditions(req);
viewData = new ViewData(null, null);
} catch (ResourceNotFoundException e) {
if (c instanceof AcceptsCreate && path.isEmpty() && ("POST".equals(req.getMethod()) || "PUT".equals(req.getMethod()))) {
@SuppressWarnings("unchecked") AcceptsCreate<RestResource> ac = (AcceptsCreate<RestResource>) c;
viewData = new ViewData(viewData.pluginName, ac.create(rsrc, id));
status = SC_CREATED;
} else if (c instanceof AcceptsDelete && path.isEmpty() && "DELETE".equals(req.getMethod())) {
@SuppressWarnings("unchecked") AcceptsDelete<RestResource> ac = (AcceptsDelete<RestResource>) c;
viewData = new ViewData(viewData.pluginName, ac.delete(rsrc, id));
status = SC_NO_CONTENT;
} else {
throw e;
}
}
if (viewData.view == null) {
viewData = view(rsrc, c, req.getMethod(), path);
}
checkRequiresCapability(viewData);
}
if (notModified(req, rsrc, viewData.view)) {
res.sendError(SC_NOT_MODIFIED);
return;
}
if (!globals.paramParser.get().parse(viewData.view, params, req, res)) {
return;
}
if (viewData.view instanceof RestReadView<?> && isRead(req)) {
result = ((RestReadView<RestResource>) viewData.view).apply(rsrc);
} else if (viewData.view instanceof RestModifyView<?, ?>) {
@SuppressWarnings("unchecked") RestModifyView<RestResource, Object> m = (RestModifyView<RestResource, Object>) viewData.view;
Type type = inputType(m);
inputRequestBody = parseRequest(req, type);
result = m.apply(rsrc, inputRequestBody);
consumeRawInputRequestBody(req, type);
} else {
throw new ResourceNotFoundException();
}
if (result instanceof Response) {
@SuppressWarnings("rawtypes") Response<?> r = (Response) result;
status = r.statusCode();
configureCaching(req, res, rsrc, viewData.view, r.caching());
} else if (result instanceof Response.Redirect) {
CacheHeaders.setNotCacheable(res);
res.sendRedirect(((Response.Redirect) result).location());
return;
} else if (result instanceof Response.Accepted) {
CacheHeaders.setNotCacheable(res);
res.setStatus(SC_ACCEPTED);
res.setHeader(HttpHeaders.LOCATION, ((Response.Accepted) result).location());
return;
} else {
CacheHeaders.setNotCacheable(res);
}
res.setStatus(status);
if (result != Response.none()) {
result = Response.unwrap(result);
if (result instanceof BinaryResult) {
responseBytes = replyBinaryResult(req, res, (BinaryResult) result);
} else {
responseBytes = replyJson(req, res, config, result);
}
}
} catch (MalformedJsonException e) {
responseBytes = replyError(req, res, status = SC_BAD_REQUEST, "Invalid " + JSON_TYPE + " in request", e);
} catch (JsonParseException e) {
responseBytes = replyError(req, res, status = SC_BAD_REQUEST, "Invalid " + JSON_TYPE + " in request", e);
} catch (BadRequestException e) {
responseBytes = replyError(req, res, status = SC_BAD_REQUEST, messageOr(e, "Bad Request"), e.caching(), e);
} catch (AuthException e) {
responseBytes = replyError(req, res, status = SC_FORBIDDEN, messageOr(e, "Forbidden"), e.caching(), e);
} catch (AmbiguousViewException e) {
responseBytes = replyError(req, res, status = SC_NOT_FOUND, messageOr(e, "Ambiguous"), e);
} catch (ResourceNotFoundException e) {
responseBytes = replyError(req, res, status = SC_NOT_FOUND, messageOr(e, "Not Found"), e.caching(), e);
} catch (MethodNotAllowedException e) {
responseBytes = replyError(req, res, status = SC_METHOD_NOT_ALLOWED, messageOr(e, "Method Not Allowed"), e.caching(), e);
} catch (ResourceConflictException e) {
responseBytes = replyError(req, res, status = SC_CONFLICT, messageOr(e, "Conflict"), e.caching(), e);
} catch (PreconditionFailedException e) {
responseBytes = replyError(req, res, status = SC_PRECONDITION_FAILED, messageOr(e, "Precondition Failed"), e.caching(), e);
} catch (UnprocessableEntityException e) {
responseBytes = replyError(req, res, status = SC_UNPROCESSABLE_ENTITY, messageOr(e, "Unprocessable Entity"), e.caching(), e);
} catch (NotImplementedException e) {
responseBytes = replyError(req, res, status = SC_NOT_IMPLEMENTED, messageOr(e, "Not Implemented"), e);
} catch (Exception e) {
status = SC_INTERNAL_SERVER_ERROR;
responseBytes = handleException(e, req, res);
} finally {
String metric = viewData != null && viewData.view != null ? globals.metrics.view(viewData) : "_unknown";
globals.metrics.count.increment(metric);
if (status >= SC_BAD_REQUEST) {
globals.metrics.errorCount.increment(metric, status);
}
if (responseBytes != -1) {
globals.metrics.responseBytes.record(metric, responseBytes);
}
globals.metrics.serverLatency.record(metric, System.nanoTime() - startNanos, TimeUnit.NANOSECONDS);
globals.auditService.dispatch(new ExtendedHttpAuditEvent(globals.webSession.get().getSessionId(), globals.currentUser.get(), req, auditStartTs, params, inputRequestBody, status, result, rsrc, viewData == null ? null : viewData.view));
}
}
use of com.google.gerrit.extensions.restapi.BinaryResult in project gerrit by GerritCodeReview.
the class RestApiServlet method stackGzip.
private static BinaryResult stackGzip(HttpServletResponse res, final BinaryResult src) throws IOException {
BinaryResult gz;
long len = src.getContentLength();
if (len < 256) {
// Do not compress very small payloads.
return src;
} else if (len <= (10 << 20)) {
gz = compress(src);
if (len <= gz.getContentLength()) {
return src;
}
} else {
gz = new BinaryResult() {
@Override
public void writeTo(OutputStream out) throws IOException {
GZIPOutputStream gz = new GZIPOutputStream(out);
src.writeTo(gz);
gz.finish();
gz.flush();
}
};
}
res.setHeader("Content-Encoding", "gzip");
return gz.setContentType(src.getContentType());
}
Aggregations