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

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

Introduction

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

Prototype

public static String toString(Readable r) throws IOException 

Source Link

Document

Reads all characters from a Readable object into a String .

Usage

From source file:io.specto.hoverfly.recorder.HoverflyFilter.java

private HoverflyRecording.HoverFlyRequest recordRequest(final HttpServletRequest request) throws IOException {
    final String path = request.getPathInfo();
    final String query = request.getQueryString();
    final String requestMethod = request.getMethod();
    final String destination = simulatedBaseUrl;
    final String requestBody = request.getReader() != null ? CharStreams.toString(request.getReader()) : "";
    return new HoverflyRecording.HoverFlyRequest(path, requestMethod, destination, query, requestBody);
}

From source file:com.google.gerrit.server.mail.send.MailSoyTofuProvider.java

private void addTemplate(SoyFileSet.Builder builder, String name) throws ProvisionException {
    // Load as a file in the mail templates directory if present.
    Path tmpl = site.mail_dir.resolve(name);
    if (Files.isRegularFile(tmpl)) {
        String content;/*from  w w w  .  j a  v a2 s. co  m*/
        // TODO(davido): Consider using JGit's FileSnapshot to cache based on
        // mtime.
        try (Reader r = Files.newBufferedReader(tmpl, StandardCharsets.UTF_8)) {
            content = CharStreams.toString(r);
        } catch (IOException err) {
            throw new ProvisionException("Failed to read template file " + tmpl.toAbsolutePath().toString(),
                    err);
        }
        builder.add(content, tmpl.toAbsolutePath().toString());
        return;
    }

    // Otherwise load the template as a resource.
    String resourcePath = "com/google/gerrit/server/mail/" + name;
    builder.add(Resources.getResource(resourcePath));
}

From source file:xziar.enhancer.activity.TaskOgActivity.java

private void initDialog() {
    if (isStu) {/*  ww w  .jav a2s  . com*/
        View content = getLayoutInflater().inflate(R.layout.dialog_confirm, null, false);
        reason = (TextView) content.findViewById(R.id.describe);
        license = (AppCompatCheckBox) content.findViewById(R.id.license);
        close = content.findViewById(R.id.action_close);
        confirm = content.findViewById(R.id.btn_confirm);
        close.setOnClickListener(this);
        confirm.setOnClickListener(this);
        confirmDlg = new AlertDialog.Builder(this).setView(content).create();
        confirmDlg.setCancelable(false);
        confirmDlg.setCanceledOnTouchOutside(false);
        try {
            InputStream ins = getResources().openRawResource(R.raw.license);
            String lictxt = CharStreams.toString(new InputStreamReader(ins, "UTF-8"));
            reason.setText(lictxt);
            ins.close();
        } catch (IOException e) {
            Log.e("ReadFile", "fail read lic", e);
        }
    } else {
        View content = getLayoutInflater().inflate(R.layout.dialog_accept, null, false);
        switcher = (ViewSwitcher) content.findViewById(R.id.switcher);
        applyerlist = (CompatRecyclerView) content.findViewById(R.id.applyerlist);
        reason = (TextView) content.findViewById(R.id.describe);
        license = (AppCompatCheckBox) content.findViewById(R.id.license);
        back = content.findViewById(R.id.action_back);
        accept = content.findViewById(R.id.btn_accept);
        switcher.setInAnimation(AnimationUtils.loadAnimation(this, android.R.anim.slide_in_left));
        switcher.setOutAnimation(AnimationUtils.loadAnimation(this, android.R.anim.slide_out_right));
        apadapter = new ApplyerAdapter(this);
        applyerlist.setAdapter(apadapter);
        apadapter.setOnItemClickListener(onChooseApplicant);
        back.setOnClickListener(this);
        accept.setOnClickListener(this);
        acceptDlg = new AlertDialog.Builder(this).setView(content).create();
        acceptDlg.setCancelable(false);
        acceptDlg.setCanceledOnTouchOutside(false);
    }
    reason.setMovementMethod(new ScrollingMovementMethod());
}

From source file:org.openqa.grid.web.servlet.RegistrationServlet.java

protected void process(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String requestJsonString;/*from  w  ww.ja va2s  .c o  m*/

    try (BufferedReader rd = new BufferedReader(new InputStreamReader(request.getInputStream()))) {
        requestJsonString = CharStreams.toString(rd);
    }
    log.fine("getting the following registration request  : " + requestJsonString);

    // getting the settings from the registration
    JsonObject json = new JsonParser().parse(requestJsonString).getAsJsonObject();

    if (!json.has("configuration")) {
        // bad request. there must be a configuration for the proxy
        throw new GridConfigurationException("No configuration received for proxy.");
    }

    final RegistrationRequest registrationRequest;
    if (isV2RegistrationRequestJson(json)) {
        // Se2 compatible request
        GridNodeConfiguration nodeConfiguration = mapV2Configuration(json.getAsJsonObject("configuration"));
        registrationRequest = new RegistrationRequest(nodeConfiguration);
        // get the "capabilities" and "id" from the v2 json request
        considerV2Json(registrationRequest.getConfiguration(), json);
    } else {
        // Se3 compatible request.
        registrationRequest = RegistrationRequest.fromJson(json);
    }

    final RemoteProxy proxy = BaseRemoteProxy.getNewInstance(registrationRequest, getRegistry());

    reply(response, "ok");

    new Thread(new Runnable() { // Thread safety reviewed
        public void run() {
            getRegistry().add(proxy);
            log.fine("proxy added " + proxy.getRemoteHost());
        }
    }).start();
}

From source file:ai.nitro.bot4j.integration.facebook.receive.webhook.impl.FacebookWebhookImpl.java

@Override
public String post(final HttpServletRequest req, final HttpServletResponse res) {
    final String result = "";

    Long botId = Long.parseLong(req.getParameter("bot_id"));

    try {// w w  w. j a  v  a 2s. c  om
        final String body = CharStreams.toString(req.getReader());
        final DefaultJsonMapper mapper = new DefaultJsonMapper();
        final WebhookObject webhookObject = mapper.toJavaObject(body, WebhookObject.class);

        for (final WebhookEntry webhookEntry : webhookObject.getEntryList()) {
            handleWebhookEntry(webhookEntry, botId);
        }
    } catch (final Exception e) {
        handleException(e);
    }

    return result;
}

From source file:com.groupon.jenkins.github.GithubWebhook.java

protected String getRequestPayload(final StaplerRequest req) throws IOException {
    return CharStreams.toString(req.getReader());
}

From source file:influent.server.spi.impl.BasicCountryLevelGeocoding.java

/**
 * Constructs a new geocoder and initialises it by loading local country data.
 *///from   w ww.  ja  v a2s .c  o  m
@SuppressWarnings("deprecation")
public BasicCountryLevelGeocoding() {
    nameList = new ArrayList<FL_Country>();
    countryMap = new HashMap<String, FL_Country>();

    final InputStream inp = BasicCountryLevelGeocoding.class.getResourceAsStream("countries.json");

    if (inp != null) {
        try {
            final String json = CharStreams
                    .toString(new BufferedReader(new InputStreamReader(inp, Charset.forName("UTF-8"))));

            final JSONArray array = new JSONArray(json);

            for (int i = 0; i < array.length(); i++) {
                final JSONObject record = array.getJSONObject(i);

                final FL_Country country = new ImmutableCountry(
                        new ImmutableGeoData(getString(record, "CountryName"), getDouble(record, "Latitude"),
                                getDouble(record, "Longitude"), getString(record, "ISOCC3")),
                        getString(record, "GlobalRegion"),
                        FL_ContinentCode.valueOf(getString(record, "ContinentCode")));

                final String isoCC2 = getString(record, "ISOCC2");
                final String fips = getString(record, "FIPS");
                final String ccTLD = getString(record, "InternetCCTLD");
                final Long isoNo = getLong(record, "ISONo");

                countryMap.put(isoCC2, country);
                countryMap.put(country.getCountry().getCc(), country);

                // add non-conflicting fips.
                if (fips != null && !countryMap.containsKey(fips)) {
                    countryMap.put(fips, country);
                }
                if (isoNo != null) {
                    countryMap.put(String.valueOf(isoNo), country);
                }

                // not necessary (same as iso 2), but...
                if (ccTLD != null && !countryMap.containsKey(ccTLD)) {
                    countryMap.put(ccTLD, country);
                }

                nameList.add(country);
            }

            // sort countries
            Collections.sort(nameList, new Comparator<FL_Country>() {
                public int compare(FL_Country o1, FL_Country o2) {
                    return o2.getCountry().getText().length() - o1.getCountry().getText().length();
                }
            });

        } catch (IOException e) {
            s_logger.error("Failed to loan countries.json", e);
        } catch (JSONException e) {
            s_logger.error("Failed to parse countries.json", e);
        } finally {
            Closeables.closeQuietly(inp);
        }

    }
}

From source file:com.example.appengine.appidentity.UrlShortener.java

/**
 * Returns a shortened URL by calling the Google URL Shortener API.
 *
 * <p>Note: Error handling elided for simplicity.
 *//*w  w w . j  av  a 2 s . co m*/
public String createShortUrl(String longUrl) throws Exception {
    ArrayList<String> scopes = new ArrayList<String>();
    scopes.add("https://www.googleapis.com/auth/urlshortener");
    final AppIdentityService appIdentity = AppIdentityServiceFactory.getAppIdentityService();
    final AppIdentityService.GetAccessTokenResult accessToken = appIdentity.getAccessToken(scopes);
    // The token asserts the identity reported by appIdentity.getServiceAccountName()
    JSONObject request = new JSONObject();
    request.put("longUrl", longUrl);

    URL url = new URL("https://www.googleapis.com/urlshortener/v1/url?pp=1");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.addRequestProperty("Content-Type", "application/json");
    connection.addRequestProperty("Authorization", "Bearer " + accessToken.getAccessToken());

    OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
    request.write(writer);
    writer.close();

    if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
        // Note: Should check the content-encoding.
        //       Any JSON parser can be used; this one is used for illustrative purposes.
        JSONTokener responseTokens = new JSONTokener(connection.getInputStream());
        JSONObject response = new JSONObject(responseTokens);
        return (String) response.get("id");
    } else {
        try (InputStream s = connection.getErrorStream();
                InputStreamReader r = new InputStreamReader(s, StandardCharsets.UTF_8)) {
            throw new RuntimeException(String.format("got error (%d) response %s from %s",
                    connection.getResponseCode(), CharStreams.toString(r), connection.toString()));
        }
    }
}

From source file:com.globocom.grou.security.KeystoneAuthFilter.java

private JsonNode getJsonFromBody(HttpServletRequest request) throws IOException {
    String bodyStr = CharStreams
            .toString(new InputStreamReader(request.getInputStream(), Charset.defaultCharset()));
    return mapper.readTree(bodyStr);
}

From source file:org.eclipse.che.plugin.urlfactory.URLFactoryBuilder.java

/**
 * Build a default factory using the provided json file or create default one
 *
 * @param jsonFileLocation//from w  w w  .  jav  a  2 s.c om
 *         location of factory json file
 * @return a factory
 */
public FactoryDto createFactory(String jsonFileLocation) {

    // Check if there is factory json file inside the repository
    if (jsonFileLocation != null) {
        String factoryJsonContent = URLFetcher.fetch(jsonFileLocation);
        if (!Strings.isNullOrEmpty(factoryJsonContent)) {
            // Adapt an old factory format to a new one if necessary
            try {
                final ByteArrayInputStream contentStream = new ByteArrayInputStream(
                        factoryJsonContent.getBytes(UTF_8));
                final InputStream newStream = factoryAdapter.adapt(contentStream);
                factoryJsonContent = CharStreams.toString(new InputStreamReader(newStream, UTF_8));
            } catch (IOException x) {
                throw new IllegalStateException(x.getLocalizedMessage(), x);
            }
            return DtoFactory.getInstance().createDtoFromJson(factoryJsonContent, FactoryDto.class);
        }
    }

    // else return a default factory
    return newDto(FactoryDto.class).withV("4.0");
}