Example usage for java.nio.charset StandardCharsets ISO_8859_1

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

Introduction

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

Prototype

Charset ISO_8859_1

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

Click Source Link

Document

ISO Latin Alphabet No.

Usage

From source file:org.springframework.http.codec.multipart.DefaultMultipartMessageReader.java

@Nullable
private static byte[] boundary(HttpMessage message) {
    MediaType contentType = message.getHeaders().getContentType();
    if (contentType != null) {
        String boundary = contentType.getParameter("boundary");
        if (boundary != null) {
            return boundary.getBytes(StandardCharsets.ISO_8859_1);
        }// ww  w . jav  a 2s.co  m
    }
    return null;
}

From source file:org.sonar.scanner.report.SourcePublisherTest.java

@Test
public void cleanLineEnds() throws Exception {
    FileUtils.write(sourceFile, "\n2\r\n3\n4\r5", StandardCharsets.ISO_8859_1);

    publisher.publish(writer);/*from   ww w .  j  a v a  2s . c o m*/

    File out = writer.getSourceFile(inputFile.batchId());
    assertThat(FileUtils.readFileToString(out, StandardCharsets.UTF_8)).isEqualTo("\n2\n3\n4\n5");
}

From source file:org.sonar.batch.report.SourcePublisherTest.java

@Test
public void cleanLineEnds() throws Exception {
    FileUtils.write(sourceFile, "\n2\r\n3\n4\r5", StandardCharsets.ISO_8859_1);

    publisher.publish(writer);/*from w  w  w.  j av  a 2s. c  om*/

    File out = writer.getSourceFile(2);
    assertThat(FileUtils.readFileToString(out, StandardCharsets.UTF_8)).isEqualTo("\n2\n3\n4\n5");
}

From source file:org.sonar.scanner.scan.filesystem.CharsetValidationTest.java

@Test
public void detectUTF16Ascii() throws CharacterCodingException {
    String text = "some text to test";
    byte[] utf16be = encode(text, StandardCharsets.UTF_16BE);
    byte[] utf16le = encode(text, StandardCharsets.UTF_16LE);
    byte[] utf8 = encode(text, StandardCharsets.UTF_8);
    byte[] iso88591 = encode(text, StandardCharsets.ISO_8859_1);
    byte[] utf32 = encode(text, Charset.forName("UTF-32LE"));

    assertThat(charsets.isUTF16(utf16le, true).charset()).isEqualTo(StandardCharsets.UTF_16LE);
    assertThat(charsets.isUTF16(utf16be, true).charset()).isEqualTo(StandardCharsets.UTF_16BE);
    // not enough nulls -> we don't know
    assertThat(charsets.isUTF16(iso88591, true).valid()).isEqualTo(Validation.MAYBE);
    assertThat(charsets.isUTF16(utf8, true).valid()).isEqualTo(Validation.MAYBE);
    // fail based on double nulls
    assertThat(charsets.isUTF16(utf32, true).valid()).isEqualTo(Validation.NO);
}

From source file:org.zalando.logbook.httpclient.RequestTest.java

@Test
public void shouldReturnContentTypesCharsetIfGiven() {
    final HttpRequest delegate = get("/");
    delegate.addHeader("Content-Type", "text/plain;charset=ISO-8859-1");
    final Request unit = unit(delegate);
    assertThat(unit.getCharset(), is(StandardCharsets.ISO_8859_1));
}

From source file:org.sonar.scanner.scan.filesystem.ByteCharsetDetectorTest.java

@Test
public void tryUserAnsii() {
    when(validation.isUTF8(any(byte[].class), anyBoolean())).thenReturn(new Result(Validation.MAYBE, null));
    when(validation.isUTF16(any(byte[].class), anyBoolean()))
            .thenReturn(Result.newValid(StandardCharsets.UTF_16));
    when(validation.isValidUTF16(any(byte[].class), anyBoolean())).thenReturn(true);
    when(validation.tryDecode(any(byte[].class), eq(StandardCharsets.ISO_8859_1))).thenReturn(true);

    charsets = new ByteCharsetDetector(validation, StandardCharsets.ISO_8859_1);
    assertThat(charsets.detect(new byte[1])).isEqualTo(StandardCharsets.ISO_8859_1);
}

From source file:org.openstreetmap.gui.persistence.JSONPersistence.java

/**
 * Stores the markers to disk./*from   w ww.  j a  v  a  2  s  .  c  o  m*/
 * 
 * @param pMarkers
 *            The marker data to persist.
 * @param pFileName
 *            The destination file.
 * @throws PersistenceException
 *             is there's any issue saving the markers.
 */
public static void storeMarkers(MapMarker[] pMarkers, String pFileName) {
    JSONObject geographyCollection = new JSONObject();
    geographyCollection.put("type", "GeometryCollection");
    JSONObject versionInfo = new JSONObject();
    versionInfo.put("geodesk-version", Version.instance().toString());
    geographyCollection.put("properties", versionInfo);
    JSONArray geometries = new JSONArray();
    for (MapMarker marker : pMarkers) {
        geometries.put(createPointObject(marker));
    }
    geographyCollection.put("geometries", geometries);
    List<String> out = new ArrayList<String>();
    out.add(geographyCollection.toString(3));
    try {
        Files.write(Paths.get(pFileName), out, StandardCharsets.ISO_8859_1);
    } catch (IOException exception) {
        throw new PersistenceException(exception);
    }
}

From source file:net.yacy.crawler.data.CacheTest.java

/**
 * Run a stress test on the Cache//  w ww .  j  a v  a  2  s . co m
 * 
 * @param args
 *            main arguments
 * @throws IOException
 *             when a error occurred
 */
public static void main(final String args[]) throws IOException {
    System.out.println("Stress test on Cache");

    /*
     * Set the root log level to WARNING to prevent filling the console with
     * too many information log messages
     */
    LogManager.getLogManager().readConfiguration(
            new ByteArrayInputStream(".level=WARNING".getBytes(StandardCharsets.ISO_8859_1)));

    /* Main control parameters. Modify values for different scenarios. */

    /* Number of concurrent test tasks */
    final int threads = 50;
    /* Number of steps in each task */
    final int steps = 10;
    /* Number of test URLs in each task */
    final int urlsPerThread = 5;
    /* Size of the generated test content */
    final int contentSize = Math.max(Cache.DEFAULT_COMPRESSOR_BUFFER_SIZE + 1,
            Cache.DEFAULT_BACKEND_BUFFER_SIZE + 1) / urlsPerThread;
    /* Cache maximum size */
    final long cacheMaxSize = Math.min(1024 * 1024 * 1024, ((long) contentSize) * 10 * urlsPerThread);
    /* Sleep time between each cache operation */
    final long sleepTime = 0;
    /* Maximum waiting time (in ms) for acquiring a synchronization lock */
    final long lockTimeout = 2000;
    /* The backend compression level */
    final int compressionLevel = Deflater.BEST_COMPRESSION;

    Cache.init(new File(System.getProperty("java.io.tmpdir") + File.separator + "yacyTestCache"), "peerSalt",
            cacheMaxSize, lockTimeout, compressionLevel);
    Cache.clear();
    System.out.println("Cache initialized with a maximum size of " + cacheMaxSize + " bytes.");

    try {
        System.out.println("Starting " + threads + " threads ...");
        long time = System.nanoTime();
        List<CacheAccessTask> tasks = new ArrayList<>();
        for (int count = 0; count < threads; count++) {
            List<DigestURL> urls = new ArrayList<>();
            for (int i = 0; i < urlsPerThread; i++) {
                urls.add(new DigestURL("http://yacy.net/" + i + "/" + count));
            }
            CacheAccessTask thread = new CacheAccessTask(urls, steps, contentSize, sleepTime);
            thread.start();
            tasks.add(thread);
        }
        /* Wait for tasks termination */
        for (CacheAccessTask task : tasks) {
            try {
                task.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        /*
         * Check consistency : cache should be empty when all tasks have
         * terminated without error
         */
        Cache.commit();
        long docCount = Cache.getActualCacheDocCount();
        if (docCount > 0) {
            System.out.println("Cache is not empty!!! Actual documents count : " + docCount);
        }

        System.out.println("All threads terminated in "
                + TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - time) + "s. Computing statistics...");
        long storeTime = 0;
        long maxStoreTime = 0;
        long getContentTime = 0;
        long maxGetContentTime = 0;
        int storeFailures = 0;
        long deleteTime = 0;
        long maxDeleteTime = 0;
        long totalSteps = 0;
        for (CacheAccessTask task : tasks) {
            storeTime += task.getStoreTime();
            maxStoreTime = Math.max(task.getMaxStoreTime(), maxStoreTime);
            getContentTime += task.getGetContentTime();
            maxGetContentTime = Math.max(task.getMaxGetContentTime(), maxGetContentTime);
            storeFailures += task.getStoreFailures();
            deleteTime += task.getDeleteTime();
            maxDeleteTime = Math.max(task.getMaxDeleteTime(), maxDeleteTime);
            totalSteps += task.getSteps();
        }
        System.out.println("Cache.store() total time (ms) : " + TimeUnit.NANOSECONDS.toMillis(storeTime));
        System.out.println("Cache.store() maximum time (ms) : " + TimeUnit.NANOSECONDS.toMillis(maxStoreTime));
        System.out.println(
                "Cache.store() mean time (ms) : " + TimeUnit.NANOSECONDS.toMillis(storeTime / totalSteps));
        System.out.println("Cache.store() failures : " + storeFailures);
        System.out.println("");
        System.out.println(
                "Cache.getContent() total time (ms) : " + TimeUnit.NANOSECONDS.toMillis(getContentTime));
        System.out.println(
                "Cache.getContent() maximum time (ms) : " + TimeUnit.NANOSECONDS.toMillis(maxGetContentTime));
        System.out.println("Cache.getContent() mean time (ms) : "
                + TimeUnit.NANOSECONDS.toMillis(getContentTime / totalSteps));
        System.out.println("Cache hits : " + Cache.getHits() + " total requests : " + Cache.getTotalRequests()
                + " ( hit rate : " + NumberFormat.getPercentInstance().format(Cache.getHitRate()) + " )");
        System.out.println("");
        System.out.println("Cache.delete() total time (ms) : " + TimeUnit.NANOSECONDS.toMillis(deleteTime));
        System.out
                .println("Cache.delete() maximum time (ms) : " + TimeUnit.NANOSECONDS.toMillis(maxDeleteTime));
        System.out.println(
                "Cache.delete() mean time (ms) : " + TimeUnit.NANOSECONDS.toMillis(deleteTime / totalSteps));
    } finally {
        try {
            Cache.close();
        } finally {
            /* Shutdown running threads */
            ArrayStack.shutdownDeleteService();
            try {
                Domains.close();
            } finally {
                ConcurrentLog.shutdown();
            }
        }
    }

}

From source file:com.torchmind.stockpile.server.controller.v1.BlacklistController.java

/**
 * Checks a hostname against the blacklist.
 *
 * @param hostname a hostname.//from  w w  w. j a v  a2 s  . c  om
 * @return a blacklist result.
 */
@Nonnull
private BlacklistResult checkHostname(@Nonnull String hostname) {
    List<String> hostnameParts = Splitter.on('.').splitToList(hostname);

    for (int i = 1; i < hostnameParts.size(); ++i) {
        String currentHostname = "*." + Joiner.on('.').join(hostnameParts.subList(i, hostnameParts.size()));
        String hash = Hashing.sha1().hashString(currentHostname, StandardCharsets.ISO_8859_1).toString();

        if (this.hashes.contains(hash)) {
            return new BlacklistResult(currentHostname, true);
        }
    }

    return new BlacklistResult(hostname, false);
}

From source file:com.bekwam.resignator.util.CryptUtils.java

public String encrypt(String encrypted, String passPhrase)
        throws IOException, PGPException, NoSuchProviderException {

    if (StringUtils.isBlank(encrypted)) {
        throw new IllegalArgumentException("encrypted text is blank");
    }/*from www . j a  va2s  .  c  o m*/

    if (StringUtils.isBlank(passPhrase)) {
        throw new IllegalArgumentException("passPhrase is required");
    }

    byte[] ciphertext = encrypt(encrypted.getBytes(StandardCharsets.ISO_8859_1), passPhrase.toCharArray());
    String ciphertext64 = Base64.getEncoder().encodeToString(ciphertext); // uses ISO_8859_1
    return ciphertext64;
}