@Override public void handle(Request request, Response response) throws Exception { removeFavorite().accept(request); response.noContent(); }
private static boolean isResponseCommitted(Response response) { Response.Stream stream = response.stream(); // Request has been aborted by the client or the response was partially streamed, nothing can been done as Tomcat has committed the response return stream instanceof ServletResponse.ServletStream && ((ServletResponse.ServletStream) stream).response().isCommitted(); }
@Override public void handle(Request request, Response response) throws Exception { response.setHeader("Cache-Control", "no-cache"); response.stream().setMediaType(SVG); try (DbSession dbSession = dbClient.openSession(false)) { ComponentDto project = support.getComponent(dbSession, request); Level qualityGateStatus = getQualityGate(dbSession, project); String result = svgGenerator.generateQualityGate(qualityGateStatus); String eTag = getETag(result); Optional<String> requestedETag = request.header("If-None-Match"); if (requestedETag.filter(eTag::equals).isPresent()) { response.stream().setStatus(304); return; } response.setHeader("ETag", eTag); write(result, response.stream().output(), UTF_8); } catch (ProjectBadgesException | ForbiddenException | NotFoundException e) { // There is an issue, so do not return any ETag but make this response expire now SimpleDateFormat sdf = new SimpleDateFormat(RFC1123_DATE, Locale.US); response.setHeader("Expires", sdf.format(new Date())); write(svgGenerator.generateError(e.getMessage()), response.stream().output(), UTF_8); } }
@Override public void handle(Request request, Response response) throws Exception { try (DbSession session = dbClient.openSession(false)) { String componentKey = request.mandatoryParam("key"); ComponentDto component = componentFinder.getByKey(session, componentKey); userSession.checkComponentPermission(UserRole.USER, component); response.stream().setMediaType("text/plain"); try (OutputStreamWriter writer = new OutputStreamWriter(response.stream().output(), StandardCharsets.UTF_8)) { HashConsumer hashFunction = new HashConsumer(writer, componentKey); dbClient.fileSourceDao().readLineHashesStream(session, component.uuid(), hashFunction); if (!hashFunction.hasData()) { response.noContent(); } } } }
@Override public void handle(Request request, Response response) throws Exception { try (JsonWriter jsonWriter = response.newJsonWriter()) { jsonWriter.setSerializeEmptys(false); writeResponse(jsonWriter); } }
@Override public void handle(Request request, Response response) throws Exception { checkState(context != null, "Webservice global context must be loaded before calling the action"); String controllerKey = request.mandatoryParam("controller"); WebService.Controller controller = context.controller(controllerKey); checkArgument(controller != null, "Controller does not exist: %s", controllerKey); String actionKey = request.mandatoryParam("action"); WebService.Action action = controller.action(actionKey); checkArgument(action != null, "Action does not exist: %s", actionKey); if (action.responseExample() == null) { response.noContent(); return; } try (JsonWriter json = response.newJsonWriter()) { json.beginObject() .prop("format", action.responseExampleFormat()) .prop("example", action.responseExampleAsString()) .endObject(); } }
@Override public void handle(Request request, Response response) throws Exception { Date timestamp = request.paramAsDateTime(TS_PARAM); if (timestamp != null && timestamp.after(server.getStartedAt())) { response.stream().setStatus(HTTP_NOT_MODIFIED).output().close(); return; } String localeParam = request.mandatoryParam(LOCALE_PARAM); Locale locale = Locale.forLanguageTag(localeParam); checkArgument(!locale.getISO3Language().isEmpty(), "'%s' cannot be parsed as a BCP47 language tag", localeParam); try (JsonWriter json = response.newJsonWriter()) { json.beginObject(); json.prop("effectiveLocale", i18n.getEffectiveLocale(locale).toLanguageTag()); json.name("messages"); json.beginObject(); i18n.getPropertyKeys().forEach(messageKey -> json.prop(messageKey, i18n.message(locale, messageKey, messageKey))); json.endObject(); json.endObject(); } } }
@Test public void send_response_headers() { Request request = new TestRequest().setPath("api/foo"); DumbResponse response = run(request, newWs("api/foo", a -> a.setHandler((req, resp) -> resp.setHeader("Content-Disposition", "attachment; filename=foo.zip")))); assertThat(response.getHeader("Content-Disposition")).isEqualTo("attachment; filename=foo.zip"); }
private void writeResponse(Response response, List<CustomMeasureDto> customMeasures, int nbCustomMeasures, ComponentDto project, Map<Integer, MetricDto> metricsById, Map<String, UserDto> usersByUuid, @Nullable Long lastAnalysisDate, SearchOptions searchOptions, @Nullable List<String> fieldsToReturn) { JsonWriter json = response.newJsonWriter(); json.beginObject(); writeUsers(json, customMeasures, project, metricsById, usersByUuid, lastAnalysisDate, fieldsToReturn); searchOptions.writeJson(json, nbCustomMeasures); json.endObject(); json.close(); }
@Override public void handle(Request request, Response response) throws Exception { addFavorite().accept(request); response.noContent(); }
@Override public void handle(Request request, Response response) throws Exception { String pluginKey = request.mandatoryParam(PLUGIN_PARAM); Optional<InstalledPlugin> file = pluginFileSystem.getInstalledPlugin(pluginKey); if (!file.isPresent()) { throw new NotFoundException("Plugin " + pluginKey + " not found"); } FileAndMd5 downloadedFile; FileAndMd5 compressedJar = file.get().getCompressedJar(); if (compressedJar != null && PACK200.equals(request.param(ACCEPT_COMPRESSIONS_PARAM))) { response.stream().setMediaType("application/octet-stream"); response.setHeader("Sonar-Compression", PACK200); response.setHeader("Sonar-UncompressedMD5", file.get().getLoadedJar().getMd5()); downloadedFile = compressedJar; } else { response.stream().setMediaType("application/java-archive"); downloadedFile = file.get().getLoadedJar(); } response.setHeader("Sonar-MD5", downloadedFile.getMd5()); try (InputStream input = FileUtils.openInputStream(downloadedFile.getFile())) { IOUtils.copyLarge(input, response.stream().output()); } } }
private static void writeResponse(Response response, List<String> tags) { try (JsonWriter json = response.newJsonWriter()) { json.beginObject().name("tags").beginArray(); tags.forEach(json::value); json.endArray().endObject(); } } }
@Override public void handle(Request request, Response response) throws Exception { RemoveRequest removeRequest = toWsRequest(request); remove(removeRequest); response.noContent(); }
@Override public void handle(Request request, Response response) throws Exception { try { response.stream().setMediaType("text/plain"); String index = batchIndex.getIndex(); checkState(index != null, "No available files"); IOUtils.write(index, response.stream().output(), UTF_8); } catch (IOException e) { throw new IllegalStateException(e); } } }
@Override public void handle(Request request, Response response) throws Exception { response.setHeader("Cache-Control", "no-cache"); response.stream().setMediaType(SVG); String metricKey = request.mandatoryParam(PARAM_METRIC); try (DbSession dbSession = dbClient.openSession(false)) { ComponentDto project = support.getComponent(dbSession, request); MetricDto metric = dbClient.metricDao().selectByKey(dbSession, metricKey); checkState(metric != null && metric.isEnabled(), "Metric '%s' hasn't been found", metricKey); LiveMeasureDto measure = getMeasure(dbSession, project, metricKey); String result = generateSvg(metric, measure); String eTag = getETag(result); Optional<String> requestedETag = request.header("If-None-Match"); if (requestedETag.filter(eTag::equals).isPresent()) { response.stream().setStatus(304); return; } response.setHeader("ETag", eTag); write(result, response.stream().output(), UTF_8); } catch (ProjectBadgesException | ForbiddenException | NotFoundException e) { // There is an issue, so do not return any ETag but make this response expire now SimpleDateFormat sdf = new SimpleDateFormat(RFC1123_DATE, Locale.US); response.setHeader("Expires", sdf.format(new Date())); write(svgGenerator.generateError(e.getMessage()), response.stream().output(), UTF_8); } }
private void writeUser(DbSession dbSession, Response response, String uuid) { try (JsonWriter json = response.newJsonWriter()) { json.beginObject(); json.name("user"); UserDto user = dbClient.userDao().selectByUuid(dbSession, uuid); checkState(user != null, "User with uuid '%s' doesn't exist", uuid); Set<String> groups = new HashSet<>(dbClient.groupMembershipDao().selectGroupsByLogins(dbSession, singletonList(uuid)).get(uuid)); userWriter.write(json, user, groups, UserJsonWriter.FIELDS); json.endObject().close(); } }
@Override public void handle(Request request, Response response) throws Exception { doHandle(toApplyTemplateWsRequest(request)); response.noContent(); }
@Override public void handle(Request request, Response response) throws Exception { // Allowed to users without admin permission: http://jira.sonarsource.com/browse/SONAR-2039 Stream stream = response.stream(); stream.setMediaType(MediaTypes.XML); try (OutputStreamWriter writer = new OutputStreamWriter(stream.output(), UTF_8); DbSession dbSession = dbClient.openSession(false)) { QProfileDto profile = wsSupport.getProfile(dbSession, QProfileReference.from(request)); response.setHeader("Content-Disposition", String.format("attachment; filename=%s.xml", profile.getKee())); backuper.backup(dbSession, profile, writer); } } }