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

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

Introduction

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

Prototype

public static long copy(Readable from, Appendable to) throws IOException 

Source Link

Document

Copies all characters between the Readable and Appendable objects.

Usage

From source file:com.github.dirkraft.jash.JashIO.java

static void _string(String s, OutputStream stream) throws JashIOException {
    // Do not close
    try {/*from w w  w . j  a v a2  s.c  om*/
        OutputStreamWriter stdout = new OutputStreamWriter(stream, Charsets.UTF_8);
        CharStreams.copy(new StringReader(s), stdout);
        stdout.flush();
    } catch (IOException e) {
        throw new JashIOException(e);
    }
}

From source file:org.onosproject.odtn.utils.YangToolUtil.java

/**
 * Converts UTF-8 CompositeStream into CharSequence.
 *
 * @param utf8Input to convert//from  ww w.  j ava  2s.  com
 * @return CharSequence
 */
public static CharSequence toCharSequence(CompositeStream utf8Input) {
    StringBuilder s = new StringBuilder();
    try {
        CharStreams.copy(new InputStreamReader(utf8Input.resourceData(), UTF_8), s);
        return s;
    } catch (IOException e) {
        log.error("Exception thrown", e);
        return null;
    }
}

From source file:org.openqa.selenium.remote.NewSessionPayload.java

private NewSessionPayload(Reader source) throws IOException {
    // Dedicate up to 10% of all RAM or 20% of available RAM (whichever is smaller) to storing this
    // payload./*from  w ww  .  j  a va2  s  . c  o m*/
    int threshold = (int) Math.min(Integer.MAX_VALUE,
            Math.min(Runtime.getRuntime().freeMemory() / 5, Runtime.getRuntime().maxMemory() / 10));

    backingStore = new FileBackedOutputStream(threshold);
    try (Writer writer = new OutputStreamWriter(backingStore, UTF_8)) {
        CharStreams.copy(source, writer);
    }

    ImmutableSet.Builder<CapabilitiesFilter> adapters = ImmutableSet.builder();
    ServiceLoader.load(CapabilitiesFilter.class).forEach(adapters::add);
    adapters.add(new ChromeFilter()).add(new EdgeFilter()).add(new FirefoxFilter())
            .add(new InternetExplorerFilter()).add(new OperaFilter()).add(new SafariFilter());
    this.adapters = adapters.build();

    ImmutableSet.Builder<CapabilityTransform> transforms = ImmutableSet.builder();
    ServiceLoader.load(CapabilityTransform.class).forEach(transforms::add);
    transforms.add(new ProxyTransform()).add(new StripAnyPlatform()).add(new W3CPlatformNameNormaliser());
    this.transforms = transforms.build();

    ImmutableSet.Builder<Dialect> dialects = ImmutableSet.builder();
    if (getOss() != null) {
        dialects.add(Dialect.OSS);
    }
    if (getAlwaysMatch() != null || getFirstMatches() != null) {
        dialects.add(Dialect.W3C);
    }
    this.dialects = dialects.build();

    validate();
}

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

private JsonObject getRequestJSON(HttpServletRequest request) throws IOException {
    JsonObject requestJSON = new JsonObject();

    try (BufferedReader rd = new BufferedReader(new InputStreamReader(request.getInputStream()))) {
        StringBuilder s = new StringBuilder();
        CharStreams.copy(rd, s);
        String json = s.toString();
        if (!"".equals(json)) {
            requestJSON = new JsonParser().parse(json).getAsJsonObject();
        }//from  ww  w .  j a v  a2 s.c  o  m
    }
    return requestJSON;
}

From source file:eu.itesla_project.modules.histo.tools.HistoDbPrintAttributesTool.java

@Override
public void run(CommandLine line) throws Exception {
    OfflineConfig config = OfflineConfig.load();
    try (HistoDbClient histoDbClient = config.getHistoDbClientFactoryClass().newInstance().create()) {
        boolean statistics = line.hasOption("statistics");
        Set<HistoDbAttributeId> attrs = new LinkedHashSet<>();
        if (!statistics && line.hasOption("add-datetime")) {
            attrs.add(HistoDbMetaAttributeId.datetime);
        }/*from   w w  w  .j  ava2s . c o  m*/
        for (String str : line.getOptionValue("attributes").split(",")) {
            attrs.add(HistoDbAttributeIdParser.parse(str));
        }
        Interval interval = Interval.parse(line.getOptionValue("interval"));
        boolean format = line.hasOption("format");
        HistoDbHorizon horizon = HistoDbHorizon.SN;
        if (line.hasOption("horizon")) {
            horizon = HistoDbHorizon.valueOf(line.getOptionValue("horizon"));
        }
        boolean async = false;
        boolean zipped = false;
        InputStream is = histoDbClient.queryCsv(statistics ? HistoQueryType.stats : HistoQueryType.data, attrs,
                interval, horizon, zipped, async);
        if (format) {
            format(is, zipped);
        } else {
            try (Reader reader = createReader(is, zipped)) {
                CharStreams.copy(reader, System.out);
            }
        }
    }
}

From source file:eu.interedition.text.Text.java

public Text write(Session session, Reader content) throws IOException {
    final FileBackedOutputStream buf = createBuffer();
    CountingWriter tempWriter = null;//from   w w w. j  ava2 s  .c om
    try {
        CharStreams.copy(content, tempWriter = new CountingWriter(new OutputStreamWriter(buf, Text.CHARSET)));
    } finally {
        Closeables.close(tempWriter, false);
    }

    Reader bufReader = null;
    try {
        return write(session, bufReader = new InputStreamReader(buf.getSupplier().getInput(), Text.CHARSET),
                tempWriter.length);
    } finally {
        Closeables.close(bufReader, false);
    }
}

From source file:annis.gui.requesthandler.LoginServletRequestHandler.java

private void doPost(VaadinSession session, VaadinRequest request, VaadinResponse response) throws IOException {

    response.setContentType("text/html");

    String username = request.getParameter("annis-login-user");
    String password = request.getParameter("annis-login-password");

    if (username != null && password != null) {
        // forget any old user information
        session.getSession().removeAttribute(AnnisBaseUI.USER_KEY);
        session.getSession().removeAttribute(AnnisBaseUI.USER_LOGIN_ERROR);

        // get the URL for the REST service
        Object annisServiceURLObject = session.getSession().getAttribute(AnnisBaseUI.WEBSERVICEURL_KEY);

        if (annisServiceURLObject == null || !(annisServiceURLObject instanceof String)) {
            log.warn("AnnisWebService.URL was not set as init parameter in web.xml");
        }/*from w ww.  j a  v  a2 s  . com*/

        String webserviceURL = (String) annisServiceURLObject;

        try {
            AnnisUser user = new AnnisUser(username, password);
            WebResource res = user.getClient().resource(webserviceURL).path("admin").path("is-authenticated");
            if ("true".equalsIgnoreCase(res.get(String.class))) {
                // everything ok, save this user configuration for re-use
                Helper.setUser(user);
            }
        } catch (ClientHandlerException ex) {
            session.getSession().setAttribute(AnnisBaseUI.USER_LOGIN_ERROR,
                    "Authentification error: " + ex.getMessage());
            response.setStatus(502); // bad gateway
        } catch (LoginDataLostException ex) {
            session.getSession().setAttribute(AnnisBaseUI.USER_LOGIN_ERROR, "Lost password in memory. Sorry.");
            response.setStatus(500); // server error
        } catch (UniformInterfaceException ex) {
            if (ex.getResponse().getStatus() == Response.Status.UNAUTHORIZED.getStatusCode()) {
                session.getSession().setAttribute(AnnisBaseUI.USER_LOGIN_ERROR, "Username or password wrong");
                response.setStatus(403); // Forbidden
            } else {
                log.error(null, ex);
                session.getSession().setAttribute(AnnisBaseUI.USER_LOGIN_ERROR,
                        "Unexpected exception: " + ex.getMessage());
                response.setStatus(500);
            }
        }

        try (OutputStreamWriter writer = new OutputStreamWriter(response.getOutputStream(), Charsets.UTF_8)) {
            String html = Resources.toString(LoginServletRequestHandler.class.getResource("closelogin.html"),
                    Charsets.UTF_8);
            CharStreams.copy(new StringReader(html), writer);
        }

    } // end if login attempt

}

From source file:org.onosproject.d.config.sync.impl.netconf.NetconfDeviceConfigSynchronizerProvider.java

@Override
public CompletableFuture<SetResponse> setConfiguration(DeviceId deviceId, SetRequest request) {
    // sanity check and handle empty change?

    // TODOs:/*from  w w  w. jav a2s  .  com*/
    // - Construct convert request object into XML
    // --  [FutureWork] may need to introduce behaviour for Device specific
    //     workaround insertion

    StringBuilder rpc = new StringBuilder();

    // - Add NETCONF envelope
    rpc.append("<rpc xmlns=\"").append(NETCONF_1_0_BASE_NAMESPACE).append('"').append(">");

    rpc.append("<edit-config>");
    rpc.append("<target>");
    // TODO directly writing to running for now
    rpc.append("<running/>");
    rpc.append("</target>\n");
    rpc.append("<config ").append(XMLNS_XC).append("=\"").append(NETCONF_1_0_BASE_NAMESPACE).append("\">");
    // TODO netconf SBI should probably be adding these envelopes once
    // netconf SBI is in better shape
    // TODO In such case netconf sbi need to define namespace externally visible.
    // ("xc" in above instance)
    // to be used to add operations on config tree nodes

    // Convert change(s) into a DataNode tree
    for (Change change : request.changes()) {
        log.trace("change={}", change);

        // TODO switch statement can probably be removed
        switch (change.op()) {
        case REPLACE:
        case UPDATE:
        case DELETE:
            // convert DataNode -> ResourceData
            ResourceData data = toResourceData(change);

            // build CompositeData
            DefaultCompositeData.Builder compositeData = DefaultCompositeData.builder();

            // add ResourceData
            compositeData.resourceData(data);

            // add AnnotatedNodeInfo operation
            compositeData.addAnnotatedNodeInfo(toAnnotatedNodeInfo(change.op(), change.path()));

            RuntimeContext yrtContext = new DefaultRuntimeContext.Builder().setDataFormat(DATAFORMAT_XML)
                    .addAnnotation(XMLNS_XC_ANNOTATION).build();
            CompositeData cdata = compositeData.build();
            log.trace("CompositeData:{}", cdata);
            CompositeStream xml = context.yangRuntime().encode(cdata, yrtContext);
            try {
                CharStreams.copy(new InputStreamReader(xml.resourceData(), UTF_8), rpc);
            } catch (IOException e) {
                log.error("IOException thrown", e);
                // FIXME handle error
            }
            break;

        default:
            log.error("Should never reach here. {}", change);
            break;
        }
    }

    // - close NETCONF envelope
    // TODO eventually these should be handled by NETCONF SBI side
    rpc.append('\n');
    rpc.append("</config>");
    rpc.append("</edit-config>");
    rpc.append("</rpc>");

    // - send requests down to the device
    NetconfSession session = getNetconfSession(deviceId);
    if (session == null) {
        log.error("No session available for {}", deviceId);
        return completedFuture(
                SetResponse.response(request, Code.FAILED_PRECONDITION, "No session for " + deviceId));
    }
    try {
        // FIXME Netconf async API is currently screwed up, need to fix
        // NetconfSession, etc.
        CompletableFuture<String> response = session.rpc(rpc.toString());
        log.trace("raw request:\n{}", rpc);
        log.trace("prettified request:\n{}", XmlString.prettifyXml(rpc));
        return response.handle((resp, err) -> {
            if (err == null) {
                log.trace("reply:\n{}", XmlString.prettifyXml(resp));
                // FIXME check response properly
                return SetResponse.ok(request);
            } else {
                return SetResponse.response(request, Code.UNKNOWN, err.getMessage());
            }
        });
    } catch (NetconfException e) {
        // TODO Handle error
        log.error("NetconfException thrown", e);
        return completedFuture(SetResponse.response(request, Code.UNKNOWN, e.getMessage()));

    }
}

From source file:io.bazel.rules.closure.http.HttpMessage.java

@Override
public final String toString() {
    StringBuilder builder = new StringBuilder(1024);
    generateHeaders(builder);/*www  . j  a va 2s.c o m*/
    Charset charset = getContentType().charset().or(StandardCharsets.UTF_8);
    try {
        if (!(payload instanceof ByteArrayInputStream)) {
            payload = new ByteArrayInputStream(ByteStreams.toByteArray(payload));
        }
        payload.mark(-1);
        CharStreams.copy(new InputStreamReader(payload, charset), builder);
        payload.reset();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return builder.toString();
}

From source file:io.appium.java_client.remote.NewAppiumSessionPayload.java

private NewAppiumSessionPayload(Reader source, boolean forceMobileJSONWP) throws IOException {
    this.forceMobileJSONWP = forceMobileJSONWP;
    // Dedicate up to 10% of all RAM or 20% of available RAM (whichever is smaller) to storing this
    // payload./*from   ww  w.  j  a  va 2s . co  m*/
    int threshold = (int) Math.min(Integer.MAX_VALUE,
            Math.min(Runtime.getRuntime().freeMemory() / 5, Runtime.getRuntime().maxMemory() / 10));

    backingStore = new FileBackedOutputStream(threshold);
    try (Writer writer = new OutputStreamWriter(backingStore, UTF_8)) {
        CharStreams.copy(source, writer);
    }

    ImmutableSet.Builder<CapabilitiesFilter> adapters = ImmutableSet.builder();
    ServiceLoader.load(CapabilitiesFilter.class).forEach(adapters::add);
    adapters.add(new ChromeFilter()).add(new EdgeFilter()).add(new FirefoxFilter())
            .add(new InternetExplorerFilter()).add(new OperaFilter()).add(new SafariFilter());
    this.adapters = adapters.build();

    ImmutableSet.Builder<CapabilityTransform> transforms = ImmutableSet.builder();
    ServiceLoader.load(CapabilityTransform.class).forEach(transforms::add);
    transforms.add(new ProxyTransform()).add(new StripAnyPlatform()).add(new W3CPlatformNameNormaliser());
    this.transforms = transforms.build();

    ImmutableSet.Builder<Dialect> dialects = ImmutableSet.builder();
    if (getOss() != null) {
        dialects.add(Dialect.OSS);
    }
    if (getAlwaysMatch() != null || getFirstMatch() != null) {
        dialects.add(Dialect.W3C);
    }

    validate();
}