Search in sources :

Example 16 with JsonWriter

use of com.google.gson.stream.JsonWriter in project intellij-community by JetBrains.

the class AboutHttpService method getAbout.

public static void getAbout(@NotNull OutputStream out, @Nullable QueryStringDecoder urlDecoder) throws IOException {
    JsonWriter writer = createJsonWriter(out);
    writer.beginObject();
    IdeAboutInfoUtil.writeAboutJson(writer);
    if (urlDecoder != null && getBooleanParameter("registeredFileTypes", urlDecoder)) {
        writer.name("registeredFileTypes").beginArray();
        for (FileType fileType : FileTypeRegistry.getInstance().getRegisteredFileTypes()) {
            writer.beginObject();
            writer.name("name").value(fileType.getName());
            writer.name("description").value(fileType.getDescription());
            writer.name("isBinary").value(fileType.isBinary());
            writer.endObject();
        }
        writer.endArray();
    }
    if (urlDecoder != null && getBooleanParameter("more", urlDecoder)) {
        ApplicationInfoEx appInfo = ApplicationInfoEx.getInstanceEx();
        writer.name("vendor").value(appInfo.getCompanyName());
        writer.name("isEAP").value(appInfo.isEAP());
        writer.name("productCode").value(appInfo.getBuild().getProductCode());
        writer.name("buildDate").value(appInfo.getBuildDate().getTime().getTime());
        writer.name("isSnapshot").value(appInfo.getBuild().isSnapshot());
        writer.name("configPath").value(PathManager.getConfigPath());
        writer.name("systemPath").value(PathManager.getSystemPath());
        writer.name("binPath").value(PathManager.getBinPath());
        writer.name("logPath").value(PathManager.getLogPath());
        writer.name("homePath").value(PathManager.getHomePath());
    }
    writer.endObject();
    writer.close();
}
Also used : ApplicationInfoEx(com.intellij.openapi.application.ex.ApplicationInfoEx) FileType(com.intellij.openapi.fileTypes.FileType) JsonWriter(com.google.gson.stream.JsonWriter)

Example 17 with JsonWriter

use of com.google.gson.stream.JsonWriter in project intellij-plugins by JetBrains.

the class JstdIntellijServerListener method formatJson.

@NotNull
private static String formatJson(@NotNull String type, @NotNull Handler handler) {
    StringWriter buf = new StringWriter();
    JsonWriter writer = new JsonWriter(buf);
    writer.setLenient(false);
    try {
        writer.beginObject();
        writer.name(JstdCommonConstants.EVENT_TYPE);
        writer.value(type);
        handler.handle(writer);
        writer.endObject();
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        try {
            writer.close();
        } catch (IOException e) {
            //noinspection CallToPrintStackTrace
            e.printStackTrace();
        }
    }
    return buf.toString();
}
Also used : StringWriter(java.io.StringWriter) IOException(java.io.IOException) JsonWriter(com.google.gson.stream.JsonWriter) NotNull(org.jetbrains.annotations.NotNull)

Example 18 with JsonWriter

use of com.google.gson.stream.JsonWriter in project cdap by caskdata.

the class StreamFetchHandler method fetch.

/**
   * Handler for the HTTP API {@code /streams/[stream_name]/events?start=[start_ts]&end=[end_ts]&limit=[event_limit]}
   * <p>
   * Responds with:
   * <ul>
   * <li>404 if stream does not exist</li>
   * <li>204 if no event in the given start/end time range exists</li>
   * <li>200 if there is are one or more events</li>
   * </ul>
   * </p>
   * <p>
   * Response body is a JSON array of the StreamEvent object.
   * </p>
   *
   * @see StreamEventTypeAdapter StreamEventTypeAdapter for the format of the StreamEvent object
   */
@GET
@Path("/{stream}/events")
public void fetch(HttpRequest request, final HttpResponder responder, @PathParam("namespace-id") String namespaceId, @PathParam("stream") String stream, @QueryParam("start") @DefaultValue("0") String start, @QueryParam("end") @DefaultValue("9223372036854775807") String end, @QueryParam("limit") @DefaultValue("2147483647") final int limitEvents) throws Exception {
    long startTime = TimeMathParser.parseTime(start, TimeUnit.MILLISECONDS);
    long endTime = TimeMathParser.parseTime(end, TimeUnit.MILLISECONDS);
    StreamId streamId = new StreamId(namespaceId, stream);
    if (!verifyGetEventsRequest(streamId, startTime, endTime, limitEvents, responder)) {
        return;
    }
    // Make sure the user has READ permission on the stream since getConfig doesn't check for the same.
    authorizationEnforcer.enforce(streamId, authenticationContext.getPrincipal(), Action.READ);
    final StreamConfig streamConfig = streamAdmin.getConfig(streamId);
    long now = System.currentTimeMillis();
    startTime = Math.max(startTime, now - streamConfig.getTTL());
    endTime = Math.min(endTime, now);
    final long streamStartTime = startTime;
    final long streamEndTime = endTime;
    impersonator.doAs(streamId, new Callable<Void>() {

        @Override
        public Void call() throws Exception {
            int limit = limitEvents;
            // Create the stream event reader
            try (FileReader<StreamEventOffset, Iterable<StreamFileOffset>> reader = createReader(streamConfig, streamStartTime)) {
                TimeRangeReadFilter readFilter = new TimeRangeReadFilter(streamStartTime, streamEndTime);
                List<StreamEvent> events = Lists.newArrayListWithCapacity(100);
                // Reads the first batch of events from the stream.
                int eventsRead = readEvents(reader, events, limit, readFilter);
                // If empty already, return 204 no content
                if (eventsRead <= 0) {
                    responder.sendStatus(HttpResponseStatus.NO_CONTENT);
                    return null;
                }
                // Send with chunk response, as we don't want to buffer all events in memory to determine the content-length.
                ChunkResponder chunkResponder = responder.sendChunkStart(HttpResponseStatus.OK, ImmutableMultimap.of(HttpHeaders.Names.CONTENT_TYPE, "application/json; charset=utf-8"));
                ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
                JsonWriter jsonWriter = new JsonWriter(new OutputStreamWriter(new ChannelBufferOutputStream(buffer), Charsets.UTF_8));
                // Response is an array of stream event
                jsonWriter.beginArray();
                while (limit > 0 && eventsRead > 0) {
                    limit -= eventsRead;
                    for (StreamEvent event : events) {
                        GSON.toJson(event, StreamEvent.class, jsonWriter);
                        jsonWriter.flush();
                        // If exceeded chunk size limit, send a new chunk.
                        if (buffer.readableBytes() >= CHUNK_SIZE) {
                            // If the connect is closed, sendChunk will throw IOException.
                            // No need to handle the exception as it will just propagated back to the netty-http library
                            // and it will handle it.
                            // Need to copy the buffer because the buffer will get reused and send chunk is an async operation
                            chunkResponder.sendChunk(buffer.copy());
                            buffer.clear();
                        }
                    }
                    events.clear();
                    if (limit > 0) {
                        eventsRead = readEvents(reader, events, limit, readFilter);
                    }
                }
                jsonWriter.endArray();
                jsonWriter.close();
                // Send the last chunk that still has data
                if (buffer.readable()) {
                    // No need to copy the last chunk, since the buffer will not be reused
                    chunkResponder.sendChunk(buffer);
                }
                Closeables.closeQuietly(chunkResponder);
            }
            return null;
        }
    });
}
Also used : ChannelBufferOutputStream(org.jboss.netty.buffer.ChannelBufferOutputStream) StreamId(co.cask.cdap.proto.id.StreamId) StreamEvent(co.cask.cdap.api.flow.flowlet.StreamEvent) StreamConfig(co.cask.cdap.data2.transaction.stream.StreamConfig) JsonWriter(com.google.gson.stream.JsonWriter) IOException(java.io.IOException) ChannelBuffer(org.jboss.netty.buffer.ChannelBuffer) FileReader(co.cask.cdap.data.file.FileReader) MultiLiveStreamFileReader(co.cask.cdap.data.stream.MultiLiveStreamFileReader) List(java.util.List) OutputStreamWriter(java.io.OutputStreamWriter) TimeRangeReadFilter(co.cask.cdap.data.stream.TimeRangeReadFilter) StreamFileOffset(co.cask.cdap.data.stream.StreamFileOffset) ChunkResponder(co.cask.http.ChunkResponder) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Example 19 with JsonWriter

use of com.google.gson.stream.JsonWriter in project Essentials by drtshock.

the class Commandcreatekit method gist.

/**
     * SEE https://developer.github.com/v3/gists/#create-a-gist
     */
private void gist(final CommandSource sender, final String kitName, final long delay, final String contents) {
    executorService.submit(new Runnable() {

        @Override
        public void run() {
            try {
                HttpURLConnection connection = (HttpURLConnection) new URL(PASTE_URL).openConnection();
                connection.setRequestMethod("POST");
                connection.setDoInput(true);
                connection.setDoOutput(true);
                try (OutputStream os = connection.getOutputStream()) {
                    StringWriter sw = new StringWriter();
                    new JsonWriter(sw).beginObject().name("description").value(sender.getSender().getName() + ": /createkit " + kitName).name("public").value(false).name("files").beginObject().name("kit.yml").beginObject().name("content").value(contents).endObject().endObject().endObject();
                    os.write(sw.toString().getBytes());
                }
                // Error
                if (connection.getResponseCode() >= 400) {
                    sender.sendMessage(tl("createKitFailed", kitName));
                    String message = CharStreams.toString(new InputStreamReader(connection.getErrorStream(), Charsets.UTF_8));
                    ess.getLogger().severe("Error creating kit: " + message);
                    return;
                }
                // Read URl
                Map<String, String> map = GSON.fromJson(new InputStreamReader(connection.getInputStream(), Charsets.UTF_8), new TypeToken<Map<String, Object>>() {
                }.getType());
                String pasteUrl = map.get("html_url");
                connection.disconnect();
                /* ================================
                     * >> Shorten URL to fit in chat
                     * ================================ */
                {
                    connection = (HttpURLConnection) new URL(SHORTENER_URL).openConnection();
                    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    connection.setDoOutput(true);
                    pasteUrl = "url=" + pasteUrl;
                    try (OutputStream os = connection.getOutputStream()) {
                        os.write(pasteUrl.getBytes());
                    }
                    pasteUrl = connection.getHeaderField("Location");
                }
                String separator = tl("createKitSeparator");
                String delayFormat = "0";
                if (delay > 0) {
                    delayFormat = DateUtil.formatDateDiff(System.currentTimeMillis() + (delay * 1000));
                }
                sender.sendMessage(separator);
                sender.sendMessage(tl("createKitSuccess", kitName, delayFormat, pasteUrl));
                sender.sendMessage(separator);
                if (ess.getSettings().isDebug()) {
                    ess.getLogger().info(sender.getSender().getName() + " created a kit: " + pasteUrl);
                }
            } catch (Exception e) {
                sender.sendMessage(tl("createKitFailed", kitName));
                e.printStackTrace();
            }
        }
    });
}
Also used : HttpURLConnection(java.net.HttpURLConnection) StringWriter(java.io.StringWriter) InputStreamReader(java.io.InputStreamReader) OutputStream(java.io.OutputStream) JsonWriter(com.google.gson.stream.JsonWriter) Map(java.util.Map) URL(java.net.URL)

Example 20 with JsonWriter

use of com.google.gson.stream.JsonWriter in project zeppelin by apache.

the class NotebookTypeAdapterFactory method customizeTypeAdapter.

private TypeAdapter<C> customizeTypeAdapter(Gson gson, TypeToken<C> type) {
    final TypeAdapter<C> delegate = gson.getDelegateAdapter(this, type);
    final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
    return new TypeAdapter<C>() {

        @Override
        public void write(JsonWriter out, C value) throws IOException {
            JsonElement tree = delegate.toJsonTree(value);
            beforeWrite(value, tree);
            elementAdapter.write(out, tree);
        }

        @Override
        public C read(JsonReader in) throws IOException {
            JsonElement tree = elementAdapter.read(in);
            afterRead(tree);
            return delegate.fromJsonTree(tree);
        }
    };
}
Also used : JsonElement(com.google.gson.JsonElement) TypeAdapter(com.google.gson.TypeAdapter) JsonReader(com.google.gson.stream.JsonReader) JsonWriter(com.google.gson.stream.JsonWriter)

Aggregations

JsonWriter (com.google.gson.stream.JsonWriter)38 StringWriter (java.io.StringWriter)16 OutputStreamWriter (java.io.OutputStreamWriter)11 Gson (com.google.gson.Gson)9 IOException (java.io.IOException)9 Test (org.junit.Test)9 JsonReader (com.google.gson.stream.JsonReader)8 Writer (java.io.Writer)7 StringReader (java.io.StringReader)5 SuppressLint (android.annotation.SuppressLint)3 JsonObject (com.google.gson.JsonObject)3 JsonDataSources (com.google.samples.apps.iosched.server.schedule.model.JsonDataSources)3 Map (java.util.Map)3 JsonElement (com.google.gson.JsonElement)2 TypeAdapter (com.google.gson.TypeAdapter)2 DataExtractor (com.google.samples.apps.iosched.server.schedule.model.DataExtractor)2 CloudFileManager (com.google.samples.apps.iosched.server.schedule.server.cloudstorage.CloudFileManager)2 ExtraInput (com.google.samples.apps.iosched.server.schedule.server.input.ExtraInput)2 VendorDynamicInput (com.google.samples.apps.iosched.server.schedule.server.input.VendorDynamicInput)2 BufferedWriter (java.io.BufferedWriter)2