Java Code Examples for java.nio.charset.Charset#defaultCharset()

The following examples show how to use java.nio.charset.Charset#defaultCharset() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 * @deprecated since 9.6.0. Use the {@link com.rapidminer.tools.io.Encoding Encoding} class instead if you cannot use UTF-8 for some reason (there should be zero reasons!)
 */
@Deprecated
public static Charset getEncoding(String encoding) {
	if (encoding == null) {
		encoding = ParameterService.getParameterValue(RapidMiner.PROPERTY_RAPIDMINER_GENERAL_DEFAULT_ENCODING);
		if (encoding == null || encoding.trim().length() == 0) {
			encoding = RapidMiner.SYSTEM_ENCODING_NAME;
		}
	}

	Charset result = null;
	if (RapidMiner.SYSTEM_ENCODING_NAME.equals(encoding)) {
		result = Charset.defaultCharset();
	} else {
		try {
			result = Charset.forName(encoding);
		} catch (IllegalArgumentException e) {
			result = Charset.defaultCharset();
		}
	}
	return result;
}
 
Example 2
Source Project: logging-log4j2   File: PerfTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Log some extra bytes to fill the memory mapped buffer to force it to remap.
 */
private void forceRemap(final int linesPerIteration, final int iterations, final IPerfTestRunner runner) {
    final int LINESEP = System.lineSeparator().getBytes(Charset.defaultCharset()).length;
    final int bytesPerLine = 0 + IPerfTestRunner.THROUGHPUT_MSG.getBytes().length;
    final int bytesWritten = bytesPerLine * linesPerIteration * iterations;
    final int threshold = 1073741824; // magic number: defined in perf9MMapLocation.xml

    int todo = threshold - bytesWritten;
    if (todo <= 0) {
        return;
    }
    final byte[] filler = new byte[4096];
    Arrays.fill(filler, (byte) 'X');
    final String str = new String(filler, Charset.defaultCharset());
    do {
        runner.log(str);
    } while ((todo -= (4096 + LINESEP)) > 0);
}
 
Example 3
Source Project: gemfirexd-oss   File: DUnitLauncher.java    License: Apache License 2.0 6 votes vote down vote up
public static void initSystemProperties(LogWriter log) {
  //fake out tests that are using a bunch of hydra stuff
  System.setProperty(GemFirePrms.GEMFIRE_NAME_PROPERTY, "gemfire1");
  String workspaceDir = System.getProperty(DUnitLauncher.WORKSPACE_DIR_PARAM) ;
  workspaceDir = workspaceDir == null ? new File(".").getAbsolutePath() : workspaceDir;
  System.setProperty("JTESTS", workspaceDir + "/tests");
  //Some of the gemfirexd dunits look for xml files in this directory.
  System.setProperty("EXTRA_JTESTS", workspaceDir + "/gemfirexd/GemFireXDTests");
  System.out.println("Using JTESTS is set to " + System.getProperty("JTESTS"));
  
  //These properties are set in build.xml when it starts dunit
  System.setProperty("gf.ldap.server", "ldap");
  System.setProperty("gf.ldap.basedn", "ou=ldapTesting,dc=pune,dc=gemstone,dc=com");
  
  //indicate that this VM is controlled by the eclipse dunit.
  isLaunched = true;
  RemoteTestModule.Master = new FakeMaster();
  DUnitEnv.set(new EclipseDUnitEnv());
  suspectGrepper = new SuspectGrepOutputStream(System.out, "STDOUT", 5, "dunit", Charset.defaultCharset());
  System.setOut(new PrintStream(suspectGrepper));
}
 
Example 4
Source Project: jprotobuf   File: ProtobufProxy.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * To generate a protobuf proxy java source code for target class.
 *
 * @param os to generate java source code
 * @param cls target class
 * @param charset charset type
 * @param codeGenerator the code generator
 * @throws IOException in case of any io relative exception.
 */
public static void dynamicCodeGenerate(OutputStream os, Class cls, Charset charset, ICodeGenerator codeGenerator)
        throws IOException {
    if (cls == null) {
        throw new NullPointerException("Parameter 'cls' is null");
    }
    if (os == null) {
        throw new NullPointerException("Parameter 'os' is null");
    }
    if (charset == null) {
        charset = Charset.defaultCharset();
    }
    String code = codeGenerator.getCode();

    os.write(code.getBytes(charset));
}
 
Example 5
@Test
public void testSignal() throws IOException, InterruptedException {
    PipedOutputStream outputStream = new PipedOutputStream();
    PipedInputStream pipedInputStream = new PipedInputStream(outputStream);
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    TerminalConnection connection = new TerminalConnection(Charset.defaultCharset(), pipedInputStream, out);
    Attributes attributes = new Attributes();
    attributes.setLocalFlag(Attributes.LocalFlag.ECHOCTL, true);
    connection.setAttributes(attributes);

    Readline readline = new Readline();
    readline.readline(connection, new Prompt(""), s -> {  });

    connection.openNonBlocking();
    outputStream.write(("FOO").getBytes());
    outputStream.flush();
    Thread.sleep(100);
    connection.getTerminal().raise(Signal.INT);
    connection.close();

    Assert.assertEquals("FOO^C"+ Config.getLineSeparator(), new String(out.toByteArray()));
}
 
Example 6
Source Project: jdk-1.7-annotated   File: Console.java    License: Apache License 2.0 6 votes vote down vote up
private Console() {
    readLock = new Object();
    writeLock = new Object();
    String csname = encoding();
    if (csname != null) {
        try {
            cs = Charset.forName(csname);
        } catch (Exception x) {}
    }
    if (cs == null)
        cs = Charset.defaultCharset();
    out = StreamEncoder.forOutputStreamWriter(
              new FileOutputStream(FileDescriptor.out),
              writeLock,
              cs);
    pw = new PrintWriter(out, true) { public void close() {} };
    formatter = new Formatter(out);
    reader = new LineReader(StreamDecoder.forInputStreamReader(
                 new FileInputStream(FileDescriptor.in),
                 readLock,
                 cs));
    rcb = new char[1024];
}
 
Example 7
Source Project: java-technology-stack   File: StreamUtilsTests.java    License: MIT License 5 votes vote down vote up
@Test
public void copyToString() throws Exception {
	Charset charset = Charset.defaultCharset();
	InputStream inputStream = spy(new ByteArrayInputStream(string.getBytes(charset)));
	String actual = StreamUtils.copyToString(inputStream, charset);
	assertThat(actual, equalTo(string));
	verify(inputStream, never()).close();
}
 
Example 8
/**
 * Sets the input file the parser is going to parse. Default charset is used.
 *
 * @param fileName the name of the file
 * @throws IOException if the file does not exist
 * @throws XmlPullParserException if an error occurs in the parser
 */
public void setInputFile( String fileName ) throws IOException, XmlPullParserException
{
    try ( Reader reader = new InputStreamReader( Files.newInputStream( Paths.get( fileName ) ), 
        Charset.defaultCharset() ) )
    {
        container.getParser().setInput( reader );
    }
}
 
Example 9
public static Runnable defend(MultiplayerGame activeGame, String testFile, User defender,
                              ArrayList<String> messages, Logger logger) {
    return new Runnable() {
        
        @Inject
        private GameManagingUtils gameManagingUtils;
        
        @Inject
        private IMutationTester mutationTester;
        
        @Override
        public void run() {
            try {
                // Compile and test original
                String testText;
                testText = new String(Files.readAllBytes(new File(testFile).toPath()), Charset.defaultCharset());
                org.codedefenders.game.Test newTest = gameManagingUtils.createTest(activeGame.getId(), activeGame.getClassId(),
                        testText, defender.getId(), Constants.MODE_BATTLEGROUND_DIR);

                System.out.println(new Date() + " MutationTesterTest.defend() " + defender.getId() + " with "
                        + newTest.getId());
                mutationTester.runTestOnAllMultiplayerMutants(activeGame, newTest, messages);
                activeGame.update();
                System.out.println(new Date() + " MutationTesterTest.defend() " + defender.getId() + ": "
                        + messages.get(messages.size() - 1));
            } catch (IOException e) {
                logger.error(e.getMessage());
            }
        }
    };
}
 
Example 10
Source Project: Spark   File: MediaPreferencePanel.java    License: Apache License 2.0 5 votes vote down vote up
private String convertSysString(String src)
{
	String res = src;  
	try {
		res = new String(src.getBytes("ISO-8859-1"),Charset.defaultCharset());
	} catch (UnsupportedEncodingException e) {
		Log.error("convertSysString" , e);
	}
	return res;
   }
 
Example 11
Source Project: netty4.0.27Learn   File: StringDecoder.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new instance with the current system character set.
 */
public StringDecoder() {
    this(Charset.defaultCharset());
}
 
Example 12
Source Project: rsocket-rpc-java   File: Client.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public M plainMetadataEncoder() {
  this.encoder = new PlainMetadataEncoder(".", Charset.defaultCharset());
  return this;
}
 
Example 13
/**
 * Test lengths when multiple entries are present
 *
 * @throws Exception
 */
@Test
public void testLdifParserLengthAndOffset() throws Exception
{
    String ldif1 = "dn: cn=app1,ou=applications,ou=conf,dc=apache,dc=org\n" +
        "cn: app1\n" +
        "objectClass: top\n" +
        "objectClass: apApplication\n" +
        "displayName:   app1   \n" +
        "dependencies:\n" +
        "envVars:\n";

    String comment = "# This comment was copied. Delete an entry. The operation will attach the LDAPv3\n" +
        "# Tree Delete Control defined in [9]. The criticality\n" +
        "# field is \"true\" and the controlValue field is\n" +
        "# absent, as required by [9].\n";

    String version = "version:   1\n";

    String ldif =
        version +
            ldif1 +
            "\n" +
            comment +
            ldif1 + "\n";

    LdifReader reader = new LdifReader( schemaManager );

    List<LdifEntry> lstEntries = null;

    try
    {
        lstEntries = reader.parseLdif( ldif );
    }
    catch ( Exception ne )
    {
        fail();
    }
    finally
    {
        reader.close();
    }

    LdifEntry entry1 = lstEntries.get( 0 );

    assertEquals( version.length() + ldif1.length(), entry1.getLengthBeforeParsing() );

    LdifEntry entry2 = lstEntries.get( 1 );

    assertEquals( ldif1.length() + comment.length(), entry2.getLengthBeforeParsing() );

    byte[] data = Strings.getBytesUtf8( ldif );

    String ldif1Bytes = new String( data, ( int ) entry1.getOffset(), entry1.getLengthBeforeParsing(),
        StandardCharsets.UTF_8 );
    assertNotNull( reader.parseLdif( ldif1Bytes ).get( 0 ) );

    String ldif2Bytes = new String( data, ( int ) entry2.getOffset(), entry2.getLengthBeforeParsing(),
        StandardCharsets.UTF_8 );
    assertNotNull( reader.parseLdif( ldif2Bytes ).get( 0 ) );

    File file = File.createTempFile( "offsetTest", "ldif" );
    file.deleteOnExit();
    OutputStreamWriter writer = new OutputStreamWriter( new FileOutputStream( file ), Charset.defaultCharset() );
    writer.write( ldif );
    writer.close();

    RandomAccessFile raf = new RandomAccessFile( file, "r" );

    LdifReader ldifReader = new LdifReader( file );

    LdifEntry rafEntry1 = ldifReader.next();

    data = new byte[rafEntry1.getLengthBeforeParsing()];
    raf.read( data, ( int ) rafEntry1.getOffset(), data.length );

    reader = new LdifReader( schemaManager );
    LdifEntry reReadeRafEntry1 = reader.parseLdif( new String( data, Charset.defaultCharset() ) ).get( 0 );
    assertNotNull( reReadeRafEntry1 );
    assertEquals( rafEntry1.getOffset(), reReadeRafEntry1.getOffset() );
    assertEquals( rafEntry1.getLengthBeforeParsing(), reReadeRafEntry1.getLengthBeforeParsing() );
    reader.close();

    LdifEntry rafEntry2 = ldifReader.next();

    data = new byte[rafEntry2.getLengthBeforeParsing()];
    raf.readFully( data, 0, data.length );

    reader = new LdifReader( schemaManager );
    LdifEntry reReadeRafEntry2 = reader.parseLdif( new String( data, Charset.defaultCharset() ) ).get( 0 );
    assertNotNull( reReadeRafEntry2 );
    assertEquals( rafEntry2.getLengthBeforeParsing(), reReadeRafEntry2.getLengthBeforeParsing() );
    reader.close();
    ldifReader.close();
    raf.close();
}
 
Example 14
private Charset getCharset(String encoding) {
    return (encoding == null) ? Charset.defaultCharset() : Charset.forName(encoding);
}
 
Example 15
public NativeGNULinuxTerminal() throws IOException {
    this(System.in,
            System.out,
            Charset.defaultCharset(),
            CtrlCBehaviour.CTRL_C_KILLS_APPLICATION);
}
 
Example 16
public String getContent( Charset charset ) {
    if( charset != Charset.defaultCharset() ) {
        return new String(content.getBytes(Charset.defaultCharset()), charset);
    }
    return content;
}
 
Example 17
public void writeStringNoNull(String value) {
    Charset cs = Charset.defaultCharset();
    writeBytes(cs.encode(value));
}
 
Example 18
Source Project: lams   File: Charsets.java    License: GNU General Public License v2.0 2 votes vote down vote up
/**
 * Returns a Charset for the named charset. If the name is null, return the default Charset.
 * 
 * @param charset
 *            The name of the requested charset, may be null.
 * @return a Charset for the named charset
 * @throws java.nio.charset.UnsupportedCharsetException
 *             If the named charset is unavailable
 */
public static Charset toCharset(final String charset) {
    return charset == null ? Charset.defaultCharset() : Charset.forName(charset);
}
 
Example 19
/**
 * Returns the given Charset or the default Charset if the given Charset is null.
 *
 * @param charset
 *            A charset or null.
 * @return the given Charset or the default Charset if the given Charset is null
 */
public static Charset toCharset(final Charset charset) {
    return charset == null ? Charset.defaultCharset() : charset;
}
 
Example 20
/**
 * Returns a Charset for the named charset. If the name is null, return the default Charset.
 *
 * @param charset
 *            The name of the requested charset, may be null.
 * @return a Charset for the named charset
 * @throws java.nio.charset.UnsupportedCharsetException
 *             If the named charset is unavailable
 */
public static Charset toCharset(final String charset) {
    return charset == null ? Charset.defaultCharset() : Charset.forName(charset);
}