Example usage for com.google.common.io CharStreams asWriter

List of usage examples for com.google.common.io CharStreams asWriter

Introduction

In this page you can find the example usage for com.google.common.io CharStreams asWriter.

Prototype

public static Writer asWriter(Appendable target) 

Source Link

Document

Returns a Writer that sends all output to the given Appendable target.

Usage

From source file:co.cask.cdap.internal.io.Schema.java

/**
 * Helper method to encode this schema into json string.
 *
 * @return A json string representing this schema.
 *//*from   w  w w.j  av a2  s . c  om*/
private String buildString() {
    if (type.isSimpleType()) {
        return '"' + type.name().toLowerCase() + '"';
    }
    StringBuilder builder = new StringBuilder();
    JsonWriter writer = new JsonWriter(CharStreams.asWriter(builder));
    try {
        new co.cask.cdap.internal.io.SchemaTypeAdapter().write(writer, this);
        writer.close();
        return builder.toString();
    } catch (IOException e) {
        // It should never throw IOException on the StringBuilder Writer, if it does, something very wrong.
        throw Throwables.propagate(e);
    }
}

From source file:co.cask.tigon.internal.io.Schema.java

/**
 * Helper method to encode this schema into json string.
 *
 * @return A json string representing this schema.
 */// w ww  .j a va  2s .co m
private String buildString() {
    if (type.isSimpleType()) {
        return '"' + type.name().toLowerCase() + '"';
    }
    StringBuilder builder = new StringBuilder();
    JsonWriter writer = new JsonWriter(CharStreams.asWriter(builder));
    try {
        new SchemaTypeAdapter().write(writer, this);
        writer.close();
        return builder.toString();
    } catch (IOException e) {
        // It should never throw IOException on the StringBuilder Writer, if it does, something very wrong.
        throw Throwables.propagate(e);
    }
}

From source file:co.cask.common.internal.io.Schema.java

/**
 * Helper method to encode this schema into json string.
 *
 * @return A json string representing this schema.
 *//*from  w  w  w . j  a  va  2s .  co m*/
private String buildString() {
    if (type.isSimpleType()) {
        return '"' + type.name().toLowerCase() + '"';
    }
    StringBuilder builder = new StringBuilder();
    JsonWriter writer = new JsonWriter(CharStreams.asWriter(builder));
    try {
        new co.cask.common.internal.io.SchemaTypeAdapter().write(writer, this);
        writer.close();
        return builder.toString();
    } catch (IOException e) {
        // It should never throw IOException on the StringBuilder Writer, if it does, something very wrong.
        throw Throwables.propagate(e);
    }
}

From source file:org.glowroot.ui.JvmJsonService.java

private String getAgentUnsupportedOperationResponse(String agentId) throws Exception {
    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb));
    try {/*from  www .  ja  v a 2  s . co  m*/
        jg.writeStartObject();
        jg.writeStringField("agentUnsupportedOperation", getAgentVersion(agentId));
        jg.writeEndObject();
    } finally {
        jg.close();
    }
    return sb.toString();
}

From source file:org.glowroot.ui.AdminJsonService.java

@POST(path = "/backend/admin/test-http-proxy", permission = "admin:edit:httpProxy")
String testHttpProxy(@BindRequest HttpProxyConfigDto configDto) throws IOException {
    // capturing newPlainPassword separately so that newPassword doesn't go through
    // encryption/decryption which has possibility of throwing
    // org.glowroot.common.repo.util.LazySecretKey.SymmetricEncryptionKeyMissingException
    HttpProxyConfigDto configDtoWithoutNewPassword;
    String passwordOverride;/* www . j a  va  2 s. c  om*/
    String newPassword = configDto.newPassword();
    if (newPassword.isEmpty()) {
        configDtoWithoutNewPassword = configDto;
        passwordOverride = null;
    } else {
        configDtoWithoutNewPassword = ImmutableHttpProxyConfigDto.builder().copyFrom(configDto).newPassword("")
                .build();
        passwordOverride = newPassword;
    }
    String testUrl = configDtoWithoutNewPassword.testUrl();
    checkNotNull(testUrl);
    URI uri;
    try {
        uri = new URI(testUrl);
    } catch (URISyntaxException e) {
        logger.debug(e.getMessage(), e);
        return createErrorResponse(e);
    }
    if (uri.getScheme() == null) {
        return createErrorResponse("Invalid url, missing protocol (e.g. http://)");
    }
    if (uri.getHost() == null) {
        return createErrorResponse("Invalid url, missing host");
    }
    String responseContent;
    try {
        responseContent = httpClient.getWithHttpProxyConfigOverride(testUrl,
                configDtoWithoutNewPassword.convert(configRepository), passwordOverride);
    } catch (Exception e) {
        logger.debug(e.getMessage(), e);
        return createErrorResponse(e);
    }
    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb));
    try {
        jg.writeStartObject();
        jg.writeStringField("content", responseContent);
        jg.writeEndObject();
    } finally {
        jg.close();
    }
    return sb.toString();
}

From source file:org.glowroot.ui.AdminJsonService.java

@POST(path = "/backend/admin/test-ldap", permission = "admin:edit:ldap")
String testLdap(@BindRequest LdapConfigDto configDto) throws Exception {
    // capturing newPlainPassword separately so that newPassword doesn't go through
    // encryption/decryption which has possibility of throwing
    // org.glowroot.common.repo.util.LazySecretKey.SymmetricEncryptionKeyMissingException
    LdapConfigDto configDtoWithoutNewPassword;
    String passwordOverride;/*from  w w  w. j a  v a 2 s .c om*/
    String newPassword = configDto.newPassword();
    if (newPassword.isEmpty()) {
        configDtoWithoutNewPassword = configDto;
        passwordOverride = null;
    } else {
        configDtoWithoutNewPassword = ImmutableLdapConfigDto.builder().copyFrom(configDto).newPassword("")
                .build();
        passwordOverride = newPassword;
    }
    LdapConfig config = configDtoWithoutNewPassword.convert(configRepository);
    String authTestUsername = checkNotNull(configDtoWithoutNewPassword.authTestUsername());
    String authTestPassword = checkNotNull(configDtoWithoutNewPassword.authTestPassword());
    Set<String> ldapGroupDns;
    try {
        ldapGroupDns = LdapAuthentication.authenticateAndGetLdapGroupDns(authTestUsername, authTestPassword,
                config, passwordOverride, configRepository.getLazySecretKey());
    } catch (AuthenticationException e) {
        logger.debug(e.getMessage(), e);
        return createErrorResponse(e);
    }
    Set<String> glowrootRoles = LdapAuthentication.getGlowrootRoles(ldapGroupDns, config);
    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb));
    try {
        jg.writeStartObject();
        jg.writeObjectField("ldapGroupDns", ldapGroupDns);
        jg.writeObjectField("glowrootRoles", glowrootRoles);
        jg.writeEndObject();
    } finally {
        jg.close();
    }
    return sb.toString();
}

From source file:co.cask.cdap.api.data.schema.Schema.java

/**
 * Helper method to encode this schema into json string.
 *
 * @return A json string representing this schema.
 *///from ww  w.  j  a v a 2 s  .c  o  m
private String buildString() {
    if (type.isSimpleType()) {
        return '"' + type.name().toLowerCase() + '"';
    }
    StringBuilder builder = new StringBuilder();
    JsonWriter writer = new JsonWriter(CharStreams.asWriter(builder));
    try {
        SCHEMA_TYPE_ADAPTER.write(writer, this);
        writer.close();
        return builder.toString();
    } catch (IOException e) {
        // It should never throw IOException on the StringBuilder Writer, if it does, something very wrong.
        throw Throwables.propagate(e);
    }
}

From source file:org.cloudsmith.geppetto.ui.editor.MetadataModel.java

synchronized void setDocument(IDocument document, IPath path, Diagnostic chain) {
    syntaxError = false;// w ww .  ja v a 2s  . c  om
    dependencyErrors = false;
    authorCall = null;
    descriptionCall = null;
    licenseCall = null;
    nameCall = null;
    projectPageCall = null;
    sourceCall = null;
    summaryCall = null;
    versionCall = null;
    dependencies.clear();
    this.document = document;
    if (document != null) {
        try {
            if (MODULEFILE_NAME.equals(path.lastSegment())) {
                if (rubyParser == null) {
                    serializer = RubyValueSerializer.INSTANCE;
                    rubyParser = new Parser();
                    rubyParserConfig = new ParserConfiguration(0, CompatVersion.RUBY1_9);
                }
                RootNode root = (RootNode) rubyParser.parse(path.toOSString(), new StringReader(document.get()),
                        rubyParserConfig);
                new LenientModulefileParser(this).parseRubyAST(root, chain);
            } else {
                if (jsonFactory == null) {
                    jsonFactory = new JsonFactory();
                    serializer = new ValueSerializer() {
                        @Override
                        public void serialize(Appendable bld, Object value) throws IOException {
                            JsonGenerator generator = jsonFactory
                                    .createJsonGenerator(CharStreams.asWriter(bld));
                            generator.setCodec(new ObjectMapper(jsonFactory));
                            generator.writeObject(value);
                            generator.flush();
                        }
                    };
                }
                new LenientMetadataJsonParser(this).parse(path.toFile(), document.get(), chain);
            }
            for (Dependency dep : dependencies) {
                boolean resolved = isResolved(dep);
                if (!resolved) {
                    FileDiagnostic diag = new FileDiagnostic(Diagnostic.ERROR, FORGE, getUnresolvedMessage(dep),
                            path.toFile());
                    diag.setLineNumber(dep.getLine());
                    chain.addChild(diag);
                    dependencyErrors = true;
                }
                dep.setResolved(resolved);
            }
        } catch (SyntaxException e) {
            syntaxError = true;
            chain.addChild(ModuleUtils.createSyntaxErrorDiagnostic(e, null));
        } catch (Exception e) {
            syntaxError = true;
            e.printStackTrace();
            chain.addChild(new ExceptionDiagnostic(Diagnostic.ERROR, PARSE_FAILURE,
                    "Unable to parse file " + path, e));
        }
    }
}

From source file:org.glowroot.ui.AdminJsonService.java

@POST(path = "/backend/admin/analyze-h2-disk-space", permission = "")
String analyzeH2DiskSpace(@BindAuthentication Authentication authentication) throws Exception {
    if (!offlineViewer && !authentication.isAdminPermitted("admin:edit:storage")) {
        throw new JsonServiceException(HttpResponseStatus.FORBIDDEN);
    }/*from   ww w.  j a va 2  s .c om*/
    long h2DataFileSize = repoAdmin.getH2DataFileSize();
    List<H2Table> tables = repoAdmin.analyzeH2DiskSpace();
    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb));
    try {
        jg.writeStartObject();
        jg.writeNumberField("h2DataFileSize", h2DataFileSize);
        jg.writeObjectField("tables", orderingByBytesDesc.sortedCopy(tables));
        jg.writeEndObject();
    } finally {
        jg.close();
    }
    return sb.toString();
}

From source file:org.glowroot.ui.AdminJsonService.java

private static String createErrorResponse(@Nullable String message) throws IOException {
    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb));
    try {/*w  w w.  j a  va2s.  co m*/
        jg.writeStartObject();
        jg.writeBooleanField("error", true);
        jg.writeStringField("message", message);
        jg.writeEndObject();
    } finally {
        jg.close();
    }
    return sb.toString();
}