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:de.bund.bfr.knime.pmm.common.chart.ChartUtilities.java

public static void saveChartAs(JFreeChart chart, String fileName, int width, int height) {
    if (fileName.toLowerCase().endsWith(".png")) {
        try {/*from   w  w w  .  j a v a2  s  . com*/
            org.jfree.chart.ChartUtilities.writeChartAsPNG(new FileOutputStream(fileName), chart, width,
                    height);
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else if (fileName.toLowerCase().endsWith(".svg")) {
        try {
            DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
            Document document = domImpl.createDocument(null, "svg", null);
            SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
            Writer outsvg = new OutputStreamWriter(new FileOutputStream(fileName), StandardCharsets.UTF_8);

            chart.draw(svgGenerator, new Rectangle2D.Double(0, 0, width, height));
            svgGenerator.stream(outsvg, true);
            outsvg.close();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (SVGGraphics2DIOException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.samczsun.helios.utils.Utils.java

public static String readProcess(Process process) {
    StringBuilder result = new StringBuilder();
    result.append("--- BEGIN PROCESS DUMP ---").append("\n");
    result.append("---- STDOUT ----").append("\n");
    InputStream inputStream = process.getInputStream();
    byte[] inputStreamBytes = new byte[0];
    try {//www . j a v a 2  s. c o  m
        inputStreamBytes = IOUtils.toByteArray(inputStream);
    } catch (IOException e) {
        result.append("An error occured while reading from stdout").append("\n");
        result.append("Caused by: ").append(e.getClass()).append(" ").append(e.getMessage()).append("\n");
    } finally {
        if (inputStreamBytes.length > 0) {
            result.append(new String(inputStreamBytes, StandardCharsets.UTF_8));
        }
    }
    result.append("---- STDERR ----").append("\n");
    inputStream = process.getErrorStream();
    inputStreamBytes = new byte[0];
    try {
        inputStreamBytes = IOUtils.toByteArray(inputStream);
    } catch (IOException e) {
        result.append("An error occured while reading from stderr").append("\n");
        result.append("Caused by: ").append(e.getClass()).append(" ").append(e.getMessage()).append("\n");
    } finally {
        if (inputStreamBytes.length > 0) {
            result.append(new String(inputStreamBytes, StandardCharsets.UTF_8));
        }
    }

    result.append("---- EXIT VALUE ----").append("\n");

    int exitValue = -0xCAFEBABE;
    try {
        exitValue = process.waitFor();
    } catch (InterruptedException e) {
        result.append("An error occured while obtaining the exit value").append("\n");
        result.append("Caused by: ").append(e.getClass()).append(" ").append(e.getMessage()).append("\n");
    } finally {
        if (exitValue != -0xCAFEBABE) {
            result.append("Process finished with exit code ").append(exitValue).append("\n");
        }
    }

    return result.toString();
}

From source file:com.heliosdecompiler.helios.handler.addons.JarLauncher.java

@Override
public void run(File file) {
    JarFile jarFile = null;//from w ww  . j a va 2s .  com
    InputStream inputStream = null;
    try {
        System.out.println("Loading addon: " + file.getAbsolutePath());
        jarFile = new JarFile(file);
        ZipEntry entry = jarFile.getEntry("addon.json");
        if (entry != null) {
            inputStream = jarFile.getInputStream(entry);
            JsonObject jsonObject = Json.parse(new InputStreamReader(inputStream, StandardCharsets.UTF_8))
                    .asObject();
            String main = jsonObject.get("main").asString();
            URL[] url = new URL[] { file.toURI().toURL() };
            ClassLoader classLoader = AccessController
                    .doPrivileged((PrivilegedAction<ClassLoader>) () -> new URLClassLoader(url,
                            Helios.class.getClassLoader()));
            Class<?> clazz = Class.forName(main, true, classLoader);
            if (Addon.class.isAssignableFrom(clazz)) {
                Addon addon = Addon.class.cast(clazz.newInstance());
                registerAddon(addon.getName(), addon);
            } else {
                throw new IllegalArgumentException("Addon main does not extend Addon");
            }
        } else {
            throw new IllegalArgumentException("No addon.json found");
        }
    } catch (Exception e) {
        ExceptionHandler.handle(e);
    } finally {
        IOUtils.closeQuietly(jarFile);
        IOUtils.closeQuietly(inputStream);
    }
}

From source file:com.liferay.mobile.android.http.file.FileUploadTest.java

@Test
public void addFileEntry() throws Exception {
    DLAppService service = new DLAppService(session);

    long repositoryId = props.getGroupId();
    long folderId = DLAppServiceTest.PARENT_FOLDER_ID;
    String fileName = DLAppServiceTest.SOURCE_FILE_NAME;
    String mimeType = DLAppServiceTest.MIME_TYPE;

    InputStream is = new ByteArrayInputStream("Hello".getBytes(StandardCharsets.UTF_8));

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();

    FileProgressCallback callback = new FileProgressCallback() {

        @Override/* w  w w.ja  va  2s. c o m*/
        public void onBytes(byte[] bytes) {
            try {
                baos.write(bytes);
            } catch (IOException ioe) {
                fail(ioe.getMessage());
            }
        }

        @Override
        public void onProgress(int totalBytes) {
            if (totalBytes == 5) {
                try {
                    baos.flush();
                } catch (IOException ioe) {
                    fail(ioe.getMessage());
                }
            }
        }

    };

    UploadData data = new UploadData(is, mimeType, fileName, callback);

    _file = service.addFileEntry(repositoryId, folderId, fileName, mimeType, fileName, "", "", data, null);

    assertEquals(fileName, _file.get(DLAppServiceTest.TITLE));
    assertEquals(5, callback.getTotal());
    assertEquals(5, baos.size());
}

From source file:io.cloudslang.lang.compiler.SlangSource.java

public static Charset getCloudSlangCharset() {
    String cslangEncoding = System.getProperty(SlangSystemPropertyConstant.CSLANG_ENCODING.getValue());
    return StringUtils.isEmpty(cslangEncoding) ? StandardCharsets.UTF_8 : Charset.forName(cslangEncoding);
}

From source file:com.heliosdecompiler.helios.controller.addons.JarLauncher.java

@Override
public void run(File file) {
    JarFile jarFile = null;//ww w.ja v a2s  .  c om
    InputStream inputStream = null;
    try {
        System.out.println("Loading addon: " + file.getAbsolutePath());
        jarFile = new JarFile(file);
        ZipEntry entry = jarFile.getEntry("addon.json");
        if (entry != null) {
            inputStream = jarFile.getInputStream(entry);
            JsonObject jsonObject = new Gson()
                    .fromJson(new InputStreamReader(inputStream, StandardCharsets.UTF_8), JsonObject.class);
            String main = jsonObject.get("main").getAsString();
            URL[] url = new URL[] { file.toURI().toURL() };
            ClassLoader classLoader = AccessController
                    .doPrivileged((PrivilegedAction<ClassLoader>) () -> new URLClassLoader(url,
                            Helios.class.getClassLoader()));
            Class<?> clazz = Class.forName(main, true, classLoader);
            if (Addon.class.isAssignableFrom(clazz)) {
                Addon addon = Addon.class.cast(clazz.newInstance());
                //                    registerAddon(addon.getName(), addon);
            } else {
                throw new IllegalArgumentException("Addon main does not extend Addon");
            }
        } else {
            throw new IllegalArgumentException("No addon.json found");
        }
    } catch (Exception e) {
        ExceptionHandler.handle(e);
    } finally {
        IOUtils.closeQuietly(jarFile);
        IOUtils.closeQuietly(inputStream);
    }
}

From source file:com.github.horrorho.inflatabledonkey.util.LZFSEExtInputStream.java

static IOException errorMessage(Process process) {
    try (InputStream is = process.getErrorStream()) {
        String message = IOUtils.toString(is, StandardCharsets.UTF_8);
        return new IOException("lzfse: " + message);
    } catch (IOException ex) {
        return ex;
    }/*w ww . ja v  a  2s. c om*/
}

From source file:ch.digitalfondue.jfiveparse.TreeConstructionTest.java

@Parameters(name = "{0}:{index}:{2}")
public static List<Object[]> data() throws IOException {
    List<Object[]> data = new ArrayList<>();
    try (DirectoryStream<Path> ds = Files
            .newDirectoryStream(Paths.get("src/test/resources/html5lib-tests/tree-construction"), "*.dat")) {
        for (Path p : ds) {
            String file = new String(Files.readAllBytes(p), StandardCharsets.UTF_8);
            String[] testsAsString = file.split("\n\n#data\n");
            for (String t : testsAsString) {
                TreeConstruction treeTest = parse(t);
                if (treeTest.scriptingFlag == null) {
                    data.add(new Object[] { p.getFileName().toString(), treeTest, false });
                    data.add(new Object[] { p.getFileName().toString(), treeTest, true });
                } else if (treeTest.scriptingFlag) {
                    data.add(new Object[] { p.getFileName().toString(), treeTest, true });
                } else {
                    data.add(new Object[] { p.getFileName().toString(), treeTest, false });
                }//  w ww  .j  a va2  s. c  o m
            }
        }
    }
    data.sort(new Comparator<Object[]>() {
        public int compare(Object[] o1, Object[] o2) {
            return new CompareToBuilder().append((String) o1[0], (String) o2[0])
                    .append((boolean) o1[2], (boolean) o2[2]).toComparison();
        }
    });
    return data;
}

From source file:org.opendatakit.utilities.LocalizationUtils.java

private static synchronized void loadTranslations(String appName, String tableId) throws IOException {
    if (savedAppName != null && !savedAppName.equals(appName)) {
        clearTranslations();//from   www  .ja  v a 2 s  .  c o  m
    }
    savedAppName = appName;
    TypeReference<HashMap<String, Object>> ref = new TypeReference<HashMap<String, Object>>() {
    };
    if (commonDefinitions == null) {
        File commonFile = new File(ODKFileUtils.getCommonDefinitionsFile(appName));
        if (commonFile.exists() && commonFile.isFile()) {
            InputStream stream = null;
            BufferedReader reader = null;
            String value;
            try {
                stream = new FileInputStream(commonFile);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8));
                } else {
                    reader = new BufferedReader(new InputStreamReader(stream, Charsets.UTF_8));
                }
                int ch = reader.read();
                while (ch != -1 && ch != '{') {
                    ch = reader.read();
                }

                StringBuilder b = new StringBuilder();
                b.append((char) ch);
                ch = reader.read();
                while (ch != -1) {
                    b.append((char) ch);
                    ch = reader.read();
                }
                reader.close();
                stream.close();
                value = b.toString().trim();
                if (value.endsWith(";")) {
                    value = value.substring(0, value.length() - 1).trim();
                }

            } finally {
                if (reader != null) {
                    reader.close();
                } else if (stream != null) {
                    stream.close();
                }
            }

            try {
                commonDefinitions = ODKFileUtils.mapper.readValue(value, ref);
            } catch (IOException e) {
                WebLogger.getLogger(appName).printStackTrace(e);
                throw new IllegalStateException("Unable to read commonDefinitions.js file");
            }
        }
    }

    if (tableId != null) {
        File tableFile = new File(ODKFileUtils.getTableSpecificDefinitionsFile(appName, tableId));
        if (!tableFile.exists()) {
            tableSpecificDefinitionsMap.remove(tableId);
        } else {
            // assume it is current if it exists
            if (tableSpecificDefinitionsMap.containsKey(tableId)) {
                return;
            }
            InputStream stream = null;
            BufferedReader reader = null;
            try {
                stream = new FileInputStream(tableFile);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8));
                } else {
                    reader = new BufferedReader(new InputStreamReader(stream, Charsets.UTF_8));
                }
                reader.mark(1);
                int ch = reader.read();
                while (ch != -1 && ch != '{') {
                    reader.mark(1);
                    ch = reader.read();
                }
                reader.reset();
                Map<String, Object> tableSpecificTranslations = ODKFileUtils.mapper.readValue(reader, ref);
                if (tableSpecificTranslations != null) {
                    tableSpecificDefinitionsMap.put(tableId, tableSpecificTranslations);
                }
            } finally {
                if (reader != null) {
                    reader.close();
                } else if (stream != null) {
                    stream.close();
                }
            }
        }
    }
}

From source file:psiprobe.controllers.sql.QueryHistoryItemController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    int sqlId = ServletRequestUtils.getIntParameter(request, "sqlId", -1);

    HttpSession sess = request.getSession(false);

    if (sess != null) {
        DataSourceTestInfo sessData = (DataSourceTestInfo) sess
                .getAttribute(DataSourceTestInfo.DS_TEST_SESS_ATTR);

        if (sessData != null) {
            List<String> queryHistory = sessData.getQueryHistory();

            if (queryHistory != null) {
                try {
                    String sql = queryHistory.get(sqlId);
                    response.setCharacterEncoding(StandardCharsets.UTF_8.name());
                    response.getWriter().print(sql);
                } catch (IndexOutOfBoundsException e) {
                    logger.error("Cannot find a query history entry for history item id = {}", sqlId);
                    logger.trace("", e);
                }//w w  w. j  a v a2 s.  c o m
            }
        }
    }

    return null;
}