Search in sources :

Example 21 with BadRequestException

use of com.google.gerrit.extensions.restapi.BadRequestException in project gerrit by GerritCodeReview.

the class InstallPlugin method apply.

@Override
public Response<PluginInfo> apply(TopLevelResource resource, Input input) throws BadRequestException, MethodNotAllowedException, IOException {
    if (!loader.isRemoteAdminEnabled()) {
        throw new MethodNotAllowedException("remote installation is disabled");
    }
    try {
        try (InputStream in = openStream(input)) {
            String pluginName = loader.installPluginFromStream(name, in);
            ListPlugins.PluginInfo info = new ListPlugins.PluginInfo(loader.get(pluginName));
            return created ? Response.created(info) : Response.ok(info);
        }
    } catch (PluginInstallException e) {
        StringWriter buf = new StringWriter();
        buf.write(String.format("cannot install %s", name));
        if (e.getCause() instanceof ZipException) {
            buf.write(": ");
            buf.write(e.getCause().getMessage());
        } else {
            buf.write(":\n");
            PrintWriter pw = new PrintWriter(buf);
            e.printStackTrace(pw);
            pw.flush();
        }
        throw new BadRequestException(buf.toString());
    }
}
Also used : PluginInfo(com.google.gerrit.server.plugins.ListPlugins.PluginInfo) MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) StringWriter(java.io.StringWriter) InputStream(java.io.InputStream) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) PluginInfo(com.google.gerrit.server.plugins.ListPlugins.PluginInfo) ZipException(java.util.zip.ZipException) PrintWriter(java.io.PrintWriter)

Example 22 with BadRequestException

use of com.google.gerrit.extensions.restapi.BadRequestException in project gerrit by GerritCodeReview.

the class PostGpgKeys method readKeysToAdd.

private List<PGPPublicKeyRing> readKeysToAdd(Input input, Set<Fingerprint> toRemove) throws BadRequestException, IOException {
    if (input.add == null || input.add.isEmpty()) {
        return ImmutableList.of();
    }
    List<PGPPublicKeyRing> keyRings = new ArrayList<>(input.add.size());
    for (String armored : input.add) {
        try (InputStream in = new ByteArrayInputStream(armored.getBytes(UTF_8));
            ArmoredInputStream ain = new ArmoredInputStream(in)) {
            @SuppressWarnings("unchecked") List<Object> objs = Lists.newArrayList(new BcPGPObjectFactory(ain));
            if (objs.size() != 1 || !(objs.get(0) instanceof PGPPublicKeyRing)) {
                throw new BadRequestException("Expected exactly one PUBLIC KEY BLOCK");
            }
            PGPPublicKeyRing keyRing = (PGPPublicKeyRing) objs.get(0);
            if (toRemove.contains(new Fingerprint(keyRing.getPublicKey().getFingerprint()))) {
                throw new BadRequestException("Cannot both add and delete key: " + keyToString(keyRing.getPublicKey()));
            }
            keyRings.add(keyRing);
        }
    }
    return keyRings;
}
Also used : PGPPublicKeyRing(org.bouncycastle.openpgp.PGPPublicKeyRing) Fingerprint(com.google.gerrit.gpg.Fingerprint) ByteArrayInputStream(java.io.ByteArrayInputStream) ArmoredInputStream(org.bouncycastle.bcpg.ArmoredInputStream) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) PublicKeyStore.keyToString(com.google.gerrit.gpg.PublicKeyStore.keyToString) PublicKeyStore.keyIdToString(com.google.gerrit.gpg.PublicKeyStore.keyIdToString) ByteArrayInputStream(java.io.ByteArrayInputStream) ArmoredInputStream(org.bouncycastle.bcpg.ArmoredInputStream) BcPGPObjectFactory(org.bouncycastle.openpgp.bc.BcPGPObjectFactory) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException)

Example 23 with BadRequestException

use of com.google.gerrit.extensions.restapi.BadRequestException in project gerrit by GerritCodeReview.

the class ParameterParser method formToJson.

@VisibleForTesting
static JsonObject formToJson(Map<String, String[]> map, Set<String> query) throws BadRequestException {
    JsonObject inputObject = new JsonObject();
    for (Map.Entry<String, String[]> ent : map.entrySet()) {
        String key = ent.getKey();
        String[] values = ent.getValue();
        if (query.contains(key) || values.length == 0) {
            // Implementations of views should avoid duplicate naming.
            continue;
        }
        JsonObject obj = inputObject;
        int dot = key.indexOf('.');
        if (0 <= dot) {
            String property = key.substring(0, dot);
            JsonElement e = inputObject.get(property);
            if (e == null) {
                obj = new JsonObject();
                inputObject.add(property, obj);
            } else if (e.isJsonObject()) {
                obj = e.getAsJsonObject();
            } else {
                throw new BadRequestException(String.format("key %s conflicts with %s", key, property));
            }
            key = key.substring(dot + 1);
        }
        if (obj.get(key) != null) {
            // again indicates something has gone very wrong.
            throw new BadRequestException("invalid form input, use JSON instead");
        } else if (values.length == 1) {
            obj.addProperty(key, values[0]);
        } else {
            JsonArray list = new JsonArray();
            for (String v : values) {
                list.add(new JsonPrimitive(v));
            }
            obj.add(key, list);
        }
    }
    return inputObject;
}
Also used : JsonArray(com.google.gson.JsonArray) JsonPrimitive(com.google.gson.JsonPrimitive) JsonElement(com.google.gson.JsonElement) JsonObject(com.google.gson.JsonObject) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) Map(java.util.Map) DynamicMap(com.google.gerrit.extensions.registration.DynamicMap) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 24 with BadRequestException

use of com.google.gerrit.extensions.restapi.BadRequestException in project gerrit by GerritCodeReview.

the class RestApiServlet method doCorsPreflight.

private void doCorsPreflight(HttpServletRequest req, HttpServletResponse res) throws BadRequestException {
    CacheHeaders.setNotCacheable(res);
    res.setHeader(VARY, Joiner.on(", ").join(ImmutableList.of(ORIGIN, ACCESS_CONTROL_REQUEST_METHOD)));
    String origin = req.getHeader(ORIGIN);
    if (Strings.isNullOrEmpty(origin) || !isOriginAllowed(origin)) {
        throw new BadRequestException("CORS not allowed");
    }
    String method = req.getHeader(ACCESS_CONTROL_REQUEST_METHOD);
    if (!"GET".equals(method) && !"HEAD".equals(method)) {
        throw new BadRequestException(method + " not allowed in CORS");
    }
    String headers = req.getHeader(ACCESS_CONTROL_REQUEST_HEADERS);
    if (headers != null) {
        res.addHeader(VARY, ACCESS_CONTROL_REQUEST_HEADERS);
        String badHeader = Streams.stream(Splitter.on(',').trimResults().split(headers)).filter(h -> !ALLOWED_CORS_REQUEST_HEADERS.contains(h)).findFirst().orElse(null);
        if (badHeader != null) {
            throw new BadRequestException(badHeader + " not allowed in CORS");
        }
    }
    res.setStatus(SC_OK);
    setCorsHeaders(res, origin);
    res.setContentType("text/plain");
    res.setContentLength(0);
}
Also used : BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) IdString(com.google.gerrit.extensions.restapi.IdString)

Example 25 with BadRequestException

use of com.google.gerrit.extensions.restapi.BadRequestException in project gerrit by GerritCodeReview.

the class CherryPickCommit method applyImpl.

@Override
public ChangeInfo applyImpl(BatchUpdate.Factory updateFactory, CommitResource rsrc, CherryPickInput input) throws OrmException, IOException, UpdateException, RestApiException {
    RevCommit commit = rsrc.getCommit();
    String message = Strings.nullToEmpty(input.message).trim();
    input.message = message.isEmpty() ? commit.getFullMessage() : message;
    String destination = Strings.nullToEmpty(input.destination).trim();
    input.parent = input.parent == null ? 1 : input.parent;
    if (destination.isEmpty()) {
        throw new BadRequestException("destination must be non-empty");
    }
    ProjectControl projectControl = rsrc.getProject();
    Capable capable = projectControl.canPushToAtLeastOneRef();
    if (capable != Capable.OK) {
        throw new AuthException(capable.getMessage());
    }
    String refName = RefNames.fullName(destination);
    RefControl refControl = projectControl.controlForRef(refName);
    if (!refControl.canUpload()) {
        throw new AuthException("Not allowed to cherry pick " + commit + " to " + destination);
    }
    Project.NameKey project = projectControl.getProject().getNameKey();
    try {
        Change.Id cherryPickedChangeId = cherryPickChange.cherryPick(updateFactory, null, null, null, null, project, commit, input, refName, refControl);
        return json.noOptions().format(project, cherryPickedChangeId);
    } catch (InvalidChangeOperationException e) {
        throw new BadRequestException(e.getMessage());
    } catch (IntegrationException e) {
        throw new ResourceConflictException(e.getMessage());
    }
}
Also used : InvalidChangeOperationException(com.google.gerrit.server.project.InvalidChangeOperationException) IntegrationException(com.google.gerrit.server.git.IntegrationException) RefControl(com.google.gerrit.server.project.RefControl) AuthException(com.google.gerrit.extensions.restapi.AuthException) Change(com.google.gerrit.reviewdb.client.Change) ProjectControl(com.google.gerrit.server.project.ProjectControl) Project(com.google.gerrit.reviewdb.client.Project) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) Capable(com.google.gerrit.common.data.Capable) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Aggregations

BadRequestException (com.google.gerrit.extensions.restapi.BadRequestException)65 AuthException (com.google.gerrit.extensions.restapi.AuthException)22 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)21 MethodNotAllowedException (com.google.gerrit.extensions.restapi.MethodNotAllowedException)15 ResourceNotFoundException (com.google.gerrit.extensions.restapi.ResourceNotFoundException)13 Repository (org.eclipse.jgit.lib.Repository)13 Project (com.google.gerrit.reviewdb.client.Project)12 UnprocessableEntityException (com.google.gerrit.extensions.restapi.UnprocessableEntityException)11 ArrayList (java.util.ArrayList)11 IOException (java.io.IOException)10 RevCommit (org.eclipse.jgit.revwalk.RevCommit)10 Account (com.google.gerrit.reviewdb.client.Account)9 Change (com.google.gerrit.reviewdb.client.Change)8 IdentifiedUser (com.google.gerrit.server.IdentifiedUser)8 BatchUpdate (com.google.gerrit.server.update.BatchUpdate)8 Map (java.util.Map)8 AccountGroup (com.google.gerrit.reviewdb.client.AccountGroup)7 ConfigInvalidException (org.eclipse.jgit.errors.ConfigInvalidException)7 RevWalk (org.eclipse.jgit.revwalk.RevWalk)7 RestApiException (com.google.gerrit.extensions.restapi.RestApiException)6