Example usage for java.nio.charset StandardCharsets UTF_8

List of usage examples for java.nio.charset StandardCharsets UTF_8

Introduction

In this page you can find the example usage for java.nio.charset StandardCharsets UTF_8.

Prototype

Charset UTF_8

To view the source code for java.nio.charset StandardCharsets UTF_8.

Click Source Link

Document

Eight-bit UCS Transformation Format.

Usage

From source file:io.cloudslang.content.database.services.SQLQueryLobService.java

public static boolean executeSqlQueryLob(SQLInputs sqlInputs) throws Exception {
    if (StringUtils.isEmpty(sqlInputs.getSqlCommand())) {
        throw new Exception("command input is empty.");
    }/*w w  w  . j a  v a 2s  . c om*/
    boolean isLOB = false;
    ConnectionService connectionService = new ConnectionService();
    try (final Connection connection = connectionService.setUpConnection(sqlInputs)) {

        StringBuilder strColumns = new StringBuilder(sqlInputs.getStrColumns());

        connection.setReadOnly(true);
        Statement statement = connection.createStatement(sqlInputs.getResultSetType(),
                sqlInputs.getResultSetConcurrency());
        statement.setQueryTimeout(sqlInputs.getTimeout());

        ResultSet results = statement.executeQuery(sqlInputs.getSqlCommand());
        ResultSetMetaData mtd = results.getMetaData();
        int iNumCols = mtd.getColumnCount();
        for (int i = 1; i <= iNumCols; i++) {
            if (i > 1)
                strColumns.append(sqlInputs.getStrDelim());
            strColumns.append(mtd.getColumnLabel(i));
        }
        sqlInputs.setStrColumns(strColumns.toString());
        int nr = -1;
        while (results.next()) {
            nr++;
            final StringBuilder strRowHolder = new StringBuilder();
            for (int i = 1; i <= iNumCols; i++) {
                if (i > 1)
                    strRowHolder.append(sqlInputs.getStrDelim());
                Object columnObject = results.getObject(i);
                if (columnObject != null) {
                    String value;
                    if (columnObject instanceof java.sql.Clob) {
                        isLOB = true;
                        final File tmpFile = File.createTempFile("CLOB_" + mtd.getColumnLabel(i), ".txt");

                        copyInputStreamToFile(
                                new ReaderInputStream(results.getCharacterStream(i), StandardCharsets.UTF_8),
                                tmpFile);

                        if (sqlInputs.getLRowsFiles().size() == nr) {
                            sqlInputs.getLRowsFiles().add(nr, new ArrayList<String>());
                            sqlInputs.getLRowsNames().add(nr, new ArrayList<String>());
                        }
                        sqlInputs.getLRowsFiles().get(nr).add(tmpFile.getAbsolutePath());
                        sqlInputs.getLRowsNames().get(nr).add(mtd.getColumnLabel(i));
                        value = "(CLOB)...";

                    } else {
                        value = results.getString(i);
                        if (sqlInputs.isNetcool())
                            value = SQLUtils.processNullTerminatedString(value);
                    }
                    strRowHolder.append(value);
                } else
                    strRowHolder.append("null");
            }
            sqlInputs.getLRows().add(strRowHolder.toString());
        }
    }

    return isLOB;
}

From source file:com.grantingersoll.opengrok.analysis.erlang.TestErlangSymbolTokenizer.java

@Test
public void test() throws Exception {
    String input;//from  w  ww  . ja v a2 s  .c om
    try (InputStream stream = TestErlangSymbolTokenizer.class.getResourceAsStream("pg_async.erl");
            Reader in = new InputStreamReader(stream, StandardCharsets.UTF_8)) {
        input = IOUtils.toString(in);
    }
    String[] output = new String[] {
            //// %%%% From https://github.com/erlang/otp/blob/maint/erts/example/pg_async.erl
            ////
            //// %%
            //// %% %CopyrightBegin%
            //// %%
            //// %% Copyright Ericsson AB 2006-2009. All Rights Reserved.
            //// %%
            //// %% Licensed under the Apache License, Version 2.0 (the "License");
            //// %% you may not use this file except in compliance with the License.
            //// %% You may obtain a copy of the License at
            //// %%
            //// %%     http://www.apache.org/licenses/LICENSE-2.0
            //// %%
            //// %% Unless required by applicable law or agreed to in writing, software
            //// %% distributed under the License is distributed on an "AS IS" BASIS,
            //// %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
            //// %% See the License for the specific language governing permissions and
            //// %% limitations under the License.
            //// %%
            //// %% %CopyrightEnd%
            //// %%
            "module", "pg_async", //// -module(pg_async).
            ////
            "define", "DRV_CONNECT", "C", //// -define(DRV_CONNECT, $C).
            "define", "DRV_DISCONNECT", "D", //// -define(DRV_DISCONNECT, $D).
            "define", "DRV_SELECT", "S", //// -define(DRV_SELECT, $S).
            ////
            "export", "connect", "disconnect", "select", //// -export([connect/1, disconnect/1, select/2]).
            ////
            "connect", "ConnectStr", //// connect(ConnectStr) ->
            "erl_ddll", "load_driver", ////     case erl_ddll:load_driver(".", "pg_async") of
            "ok", "ok", ////    ok -> ok;
            "error", "already_loaded", "ok", ////    {error, already_loaded} -> ok;
            "E", "exit", "E", ////    E -> exit(E)
            ////     end,
            "Port", "open_port", "spawn", "MODULE", "binary", ////     Port = open_port({spawn, ?MODULE}, [binary]),
            "port_control", "Port", "DRV_CONNECT", "ConnectStr", ////     port_control(Port, ?DRV_CONNECT, ConnectStr),
            "return_port_data", "Port", ////     case return_port_data(Port) of
            "ok", ////    ok ->
            "ok", "Port", ////        {ok, Port};
            "Error", ////    Error ->
            "Error", ////        Error
            ////     end.
            ////
            "disconnect", "Port", //// disconnect(Port) ->
            "port_control", "Port", "DRV_DISCONNECT", ////     port_control(Port, ?DRV_DISCONNECT, ""),
            "R", "return_port_data", "Port", ////     R = return_port_data(Port),
            "port_close", "Port", ////     port_close(Port),
            "R", ////     R.
            ////
            "select", "Port", "Query", //// select(Port, Query) ->
            "port_control", "Port", "DRV_SELECT", "Query", ////     port_control(Port, ?DRV_SELECT, Query),
            "return_port_data", "Port", ////     return_port_data(Port).
            ////
            "return_port_data", "Port", //// return_port_data(Port) ->
            ////     receive
            "Port", "data", "Data", ////    {Port, {data, Data}} ->
            "binary_to_term", "Data", ////        binary_to_term(Data)
                                      ////     end.
                                      ////
    };
    assertAnalyzesTo(analyzer, input, output);
}

From source file:com.thoughtworks.go.domain.AccessTokenTest.java

@Test
void hashToken_shouldHashTheProvidedString() throws Exception {
    AccessToken.AccessTokenWithDisplayValue token = AccessToken.create(null, null, null, new TestingClock());

    SecretKey key = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256")
            .generateSecret(new PBEKeySpec(token.getDisplayValue().substring(8).toCharArray(),
                    token.getSaltValue().getBytes(StandardCharsets.UTF_8), 4096, 256));

    assertThat(token.getValue()).isEqualTo(Hex.encodeHexString(key.getEncoded()));
}

From source file:com.expedia.seiso.web.httpmessageconverter.ItemKeyHttpMessageConverter.java

@Override
protected ItemKey readInternal(Class<? extends ItemKey> clazz, HttpInputMessage inputMessage)
        throws IOException, HttpMessageNotReadableException {

    val uri = StreamUtils.copyToString(inputMessage.getBody(), StandardCharsets.UTF_8);
    return uriToItemKeyConverter.convert(uri);
}

From source file:cz.muni.fi.mir.mathmlunificator.MathMLUnificatorCommandLineToolTest.java

@Test
public void testMain_multiple_formulae_operators() throws Exception {

    String testFile = "multiple-formulae";

    String[] argv = { "-p", getTestResourceAsFilepath(testFile + ".input.xml") };

    ByteArrayOutputStream stdoutContent = new ByteArrayOutputStream();
    PrintStream stdout = System.out;

    System.setOut(new PrintStream(stdoutContent));
    MathMLUnificatorCommandLineTool.main(argv);
    System.setOut(stdout);// w ww .ja va2  s. c o m

    String output = stdoutContent.toString(StandardCharsets.UTF_8.toString());

    System.out.println("testMain_multiple_formulae_operators  operators output:\n" + output);
    assertEquals(IOUtils.toString(getExpectedXMLTestResource(testFile + ".operator"), StandardCharsets.UTF_8),
            output);

}

From source file:ch.cyberduck.core.manta.MantaPublicKeyAuthenticationTest.java

@Test
public void testAuthenticateOpenSSHKeyWithoutPassphrase() throws Exception {
    Assume.assumeNotNull(System.getProperty("manta.url"), System.getProperty("manta.key_id"),
            System.getProperty("manta.key_path"));

    final Credentials credentials = new Credentials(System.getProperty("manta.user"), "");
    final Local key = new Local(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
    credentials.setIdentity(key);//from  www .  ja v a2s  .  co m

    try {
        new DefaultLocalTouchFeature().touch(key);
        IOUtils.copy(new FileReader(System.getProperty("manta.key_path")), key.getOutputStream(false),
                StandardCharsets.UTF_8);
        final String hostname = new URL(System.getProperty("manta.url")).getHost();
        final Host host = new Host(new MantaProtocol(), hostname, credentials);
        final MantaSession session = new MantaSession(host, new DisabledX509TrustManager(),
                new DefaultX509KeyManager());
        session.open(new DisabledHostKeyCallback());
        session.login(new DisabledPasswordStore(), new DisabledLoginCallback() {
            @Override
            public Credentials prompt(final Host bookmark, final String username, final String title,
                    final String reason, final LoginOptions options) throws LoginCanceledException {
                // no passphrase to set
                return null;
            }
        }, new DisabledCancelCallback());
        assertEquals(session.getClient().getContext().getMantaKeyId(), System.getProperty("manta.key_id"));
        session.close();
    } finally {
        key.delete();
    }
}

From source file:cherry.foundation.download.TableDownloadTemplateTest.java

@Test
public void testDownloadCsvNoHeader() throws IOException {
    // //from w ww  .  ja  v  a  2 s  .  c o  m
    MockHttpServletResponse response = new MockHttpServletResponse();
    // 
    tableDownloadOperation.downloadCsv(response, StandardCharsets.UTF_8, "test_{0}.csv",
            new LocalDateTime(2015, 1, 23, 12, 34, 56), null, createCommonClause(), createOrderByClause(),
            constant("TEST00"));
    // 
    assertEquals("text/csv", response.getContentType());
    assertEquals("UTF-8", response.getCharacterEncoding());
    assertEquals("text/csv;charset=UTF-8", response.getHeader("Content-Type"));
    assertEquals("attachment; filename=\"test_20150123123456.csv\"", response.getHeader("Content-Disposition"));
    assertEquals("\"TEST00\"\r\n", response.getContentAsString());
}

From source file:cn.edu.zjnu.acm.judge.config.UnicodeTest.java

private void test0(String laughCry) throws SQLException {
    try (Connection connection = dataSource.getConnection()) {
        connection.prepareStatement(//from ww w  .j ava  2s  . co m
                "CREATE TABLE `test_table1`(`id` INT NOT NULL, `value` LONGTEXT NULL, PRIMARY KEY (`id`) ) COLLATE='utf8mb4_general_ci'")
                .execute();
        try {
            try (PreparedStatement ps = connection
                    .prepareStatement("insert into test_table1(id,value)values(1,?)")) {
                ps.setBytes(1, laughCry.getBytes(StandardCharsets.UTF_8));
                ps.executeUpdate();
            }
            try (PreparedStatement ps = connection
                    .prepareStatement("insert into test_table1(id,value)values(2,?)")) {
                ps.setString(1, laughCry);
                ps.executeUpdate();
            }
            try (PreparedStatement ps = connection
                    .prepareStatement("select value from test_table1 where id in(1,2)");
                    ResultSet rs = ps.executeQuery()) {
                while (rs.next()) {
                    assertEquals(laughCry, rs.getString(1));
                }
            }
        } finally {
            connection.prepareStatement("DROP TABLE `test_table1`").execute();
        }
    }
}

From source file:springfox.documentation.staticdocs.SwaggerResultHandler.java

/**
 * Apply the action on the given result.
 *
 * @param result the result of the executed request
 * @throws Exception if a failure occurs
 *//*from w  w w  .  j ava  2  s. c o  m*/
@Override
public void handle(MvcResult result) throws Exception {
    MockHttpServletResponse response = result.getResponse();
    String swaggerJson = response.getContentAsString();
    Files.createDirectories(Paths.get(outputDir));
    try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputDir, fileName),
            StandardCharsets.UTF_8)) {
        writer.write(swaggerJson);
    }
}

From source file:com.grantingersoll.opengrok.analysis.vb.TestVBSymbolTokenizer.java

@Test
public void test() throws Exception {
    String input;// ww w.  j a v a  2  s.  co m
    try (InputStream stream = TestVBSymbolTokenizer.class.getResourceAsStream("VBP_pngnqInterface.bas");
            Reader in = new InputStreamReader(stream, StandardCharsets.UTF_8)) {
        input = IOUtils.toString(in);
    }
    String[] output = new String[] {
            //// ''''From https://github.com/tannerhelland/PhotoDemon/blob/master/Modules/VBP_pngnqInterface.bas
            ////
            "Attribute", "VB_Name", //// Attribute VB_Name = "Plugin_PNGQuant_Interface"
            //// '***************************************************************************
            //// 'PNGQuant Interface (formerly pngnq-s9 interface)
            //// 'Copyright 2012-2015 by Tanner Helland
            //// 'Created: 19/December/12
            //// 'Last updated: 02/July/14
            //// 'Last update: migrate all plugin support to the official pngquant library.  Work on pngnq-s9 has pretty much
            //// '              evaporated since late 2012, so pngquant is the new workhorse for PD's specialized PNG needs.
            //// '
            //// 'Module for handling all PNGQuant interfacing.  This module is pointless without the accompanying
            //// ' PNGQuant plugin, which will be in the App/PhotoDemon/Plugins subdirectory as "pngquant.exe"
            //// '
            //// 'PNGQuant is a free, open-source lossy PNG compression library.  You can learn more about it here:
            //// '
            //// ' http://pngquant.org/
            //// '
            //// 'PhotoDemon has been designed against v2.1.1 (02 July '14).  It may not work with other versions.
            //// ' Additional documentation regarding the use of PNGQuant is available as part of the official PNGQuant library,
            //// ' downloadable from http://pngquant.org/.
            //// '
            //// 'PNGQuant is available under a BSD license.  Please see the App/PhotoDemon/Plugins/pngquant-README.txt file
            //// ' for questions regarding copyright or licensing.
            //// '
            //// 'All source code in this file is licensed under a modified BSD license.  This means you may use the code in your own
            //// ' projects IF you provide attribution.  For more information, please visit http://photodemon.org/about/license/
            //// '
            //// '***************************************************************************
            ////
            "Explicit", //// Option Explicit
            ////
            //// 'Is PNGQuant.exe available on this PC?
            "isPngQuantAvailable", //// Public Function isPngQuantAvailable() As Boolean
            ////
            "cFile", "pdFSO", ////     Dim cFile As pdFSO
            "cFile", "pdFSO", ////     Set cFile = New pdFSO
            ////
            "cFile", "FileExist", "g_PluginPath", "isPngQuantAvailable", "isPngQuantAvailable", ////     If cFile.FileExist(g_PluginPath & "pngquant.exe") Then isPngQuantAvailable = True Else isPngQuantAvailable = False
            ////
            //// End Function
            ////
            //// 'Retrieve the PNGQuant plugin version.  Shelling the executable with the "--version" tag will cause it to return
            //// ' the current version (and compile date) over stdout.
            "getPngQuantVersion", //// Public Function getPngQuantVersion() As String
            ////
            "isPngQuantAvailable", ////     If Not isPngQuantAvailable Then
            "getPngQuantVersion", ////         getPngQuantVersion = ""
            ////         Exit Function
            ////
            ////     Else
            ////
            "pngqPath", ////         Dim pngqPath As String
            "pngqPath", "g_PluginPath", ////         pngqPath = g_PluginPath & "pngquant.exe"
            ////
            "outputString", ////         Dim outputString As String
            "ShellExecuteCapture", "pngqPath", "outputString", ////         If ShellExecuteCapture(pngqPath, "pngquant.exe --version", outputString) Then
            ////
            ////             'The output string will be a simple version number and release date, e.g. "2.1.1 (February 2014)".
            ////             ' Split the output by spaces, then retrieve the first entry.
            "outputString", "Trim", "outputString", ////             outputString = Trim$(outputString)
            ////
            "versionParts", ////             Dim versionParts() As String
            "versionParts", "Split", "outputString", ////             versionParts = Split(outputString, " ")
            "getPngQuantVersion", "versionParts", ////             getPngQuantVersion = versionParts(0) & ".0"
            ////
            ////         Else
            "getPngQuantVersion", ////             getPngQuantVersion = ""
                                  ////         End If
                                  ////
                                  ////     End If
                                  ////
                                  //// End Function
                                  ////
    };
    assertAnalyzesTo(analyzer, input, output);
}