Example usage for java.nio.charset Charset defaultCharset

List of usage examples for java.nio.charset Charset defaultCharset

Introduction

In this page you can find the example usage for java.nio.charset Charset defaultCharset.

Prototype

Charset defaultCharset

To view the source code for java.nio.charset Charset defaultCharset.

Click Source Link

Usage

From source file:com.khepry.utilities.GenericUtilities.java

public static void displayLogFile(String logFilePath, long logSleepMillis, String xsltFilePath,
        String xsldFilePath) {/*from w ww .  j  av  a 2s  . c  o  m*/
    Logger.getLogger("").getHandlers()[0].close();
    // only display the log file
    // if the logSleepMillis property
    // is greater than zero milliseconds
    if (logSleepMillis > 0) {
        try {
            Thread.sleep(logSleepMillis);
            File logFile = new File(logFilePath);
            File xsltFile = new File(xsltFilePath);
            File xsldFile = new File(xsldFilePath);
            File tmpFile = File.createTempFile("tmpLogFile", ".xhtml", logFile.getParentFile());
            if (logFile.exists()) {
                if (xsltFile.exists() && xsldFile.exists()) {
                    String xslFilePath;
                    String xslFileName;
                    String dtdFilePath;
                    String dtdFileName;
                    try {
                        xslFileName = new File(logFilePath).getName().replace(".xhtml", ".xsl");
                        xslFilePath = logFile.getParentFile().toString().concat("/").concat(xslFileName);
                        FileUtils.copyFile(new File(xsltFilePath), new File(xslFilePath));
                        dtdFileName = new File(logFilePath).getName().replace(".xhtml", ".dtd");
                        dtdFilePath = logFile.getParentFile().toString().concat("/").concat(dtdFileName);
                        FileUtils.copyFile(new File(xsldFilePath), new File(dtdFilePath));
                    } catch (IOException ex) {
                        String message = Level.SEVERE.toString().concat(": ").concat(ex.getLocalizedMessage());
                        Logger.getLogger(GenericUtilities.class.getName()).log(Level.SEVERE, message, ex);
                        GenericUtilities.outputToSystemErr(message, logSleepMillis > 0);
                        return;
                    }
                    BufferedWriter bw = Files.newBufferedWriter(Paths.get(tmpFile.getAbsolutePath()),
                            Charset.defaultCharset(), StandardOpenOption.CREATE);
                    List<String> logLines = Files.readAllLines(Paths.get(logFilePath),
                            Charset.defaultCharset());
                    for (String line : logLines) {
                        if (line.startsWith("<!DOCTYPE log SYSTEM \"logger.dtd\">")) {
                            bw.write("<!DOCTYPE log SYSTEM \"" + dtdFileName + "\">\n");
                            bw.write("<?xml-stylesheet type=\"text/xsl\" href=\"" + xslFileName + "\"?>\n");
                        } else {
                            bw.write(line.concat("\n"));
                        }
                    }
                    bw.write("</log>\n");
                    bw.close();
                }
                // the following statement is commented out because it's not quite ready for prime-time yet
                // Files.write(Paths.get(logFilePath), transformLogViaXSLT(logFilePath, xsltFilePath).getBytes(), StandardOpenOption.CREATE);
                Desktop.getDesktop().open(tmpFile);
            } else {
                Logger.getLogger(GenericUtilities.class.getName()).log(Level.SEVERE, logFilePath,
                        new FileNotFoundException());
            }
        } catch (InterruptedException | IOException ex) {
            Logger.getLogger(GenericUtilities.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:ca.sparkera.adapters.mainframe.CobolSerdeUtils.java

/**
 * Determine the layout to that's been provided for cobol serde work.
 * /*  w  ww  .j a va  2 s .  c  o m*/
 * @param properties
 *            containing a key pointing to the layout, one way or another
 * @return layout to use while serdeing the avro file
 * @throws IOException
 *             if error while trying to read the layout from another
 *             location
 * @throws CobolSerdeException
 *             if unable to find a layout or pointer to it in the properties
 */
public static String determineLayoutOrThrowException(Configuration conf, Properties properties)
        throws IOException, CobolSerdeException {

    //For fixed length record get length of the file 
    String fixedRecordLength = properties.getProperty(CobolTableProperties.FB_LENGTH.getPropName());
    if (fixedRecordLength != null) {
        conf.setInt(FixedLengthInputFormat.FIXED_RECORD_LENGTH, Integer.parseInt(fixedRecordLength));
    }

    String layoutString = properties.getProperty(CobolTableProperties.LAYOUT_LITERAL.getPropName());
    if (layoutString != null && !layoutString.equals(LAYOUT_NONE))
        return CobolSerdeUtils.getLayoutFor(layoutString);

    //For testing purpose
    layoutString = properties.getProperty(CobolTableProperties.LAYOUT_TEST.getPropName());
    if (layoutString != null) {
        return readFile(layoutString, Charset.defaultCharset());
    }

    // Try pulling directly from URL
    layoutString = properties.getProperty(CobolTableProperties.LAYOUT_URL.getPropName());
    if (layoutString == null || layoutString.equals(LAYOUT_NONE))
        throw new CobolSerdeException(EXCEPTION_MESSAGE);

    try {
        String s = getLayoutFromFS(layoutString, conf);
        if (s == null) {
            // in case layout is not a file system

            return CobolSerdeUtils.getLayoutFor(new URL(layoutString).openStream());
        }
        return s;
    } catch (IOException ioe) {
        throw new CobolSerdeException("Unable to read layout from given path: " + layoutString, ioe);
    } catch (URISyntaxException urie) {
        throw new CobolSerdeException("Unable to read layout from given path: " + layoutString, urie);
    }
}

From source file:org.apache.curator.x.rpc.configuration.ConfigurationBuilder.java

public Configuration build() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new LogbackModule());
    mapper.setPropertyNamingStrategy(new AnnotationSensitivePropertyNamingStrategy());
    SubtypeResolver subtypeResolver = new StdSubtypeResolver();
    subtypeResolver.registerSubtypes(ConsoleAppenderFactory.class, FileAppenderFactory.class,
            SyslogAppenderFactory.class, ExponentialBackoffRetryConfiguration.class,
            RetryNTimesConfiguration.class);
    mapper.setSubtypeResolver(subtypeResolver);

    ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
    ConfigurationFactoryFactory<Configuration> factoryFactory = new DefaultConfigurationFactoryFactory<Configuration>();
    ConfigurationFactory<Configuration> configurationFactory = factoryFactory.create(Configuration.class,
            validatorFactory.getValidator(), mapper, "curator");
    ConfigurationSourceProvider provider = new ConfigurationSourceProvider() {
        @Override/*from  w  w w  . j  av a  2  s.  c om*/
        public InputStream open(String path) throws IOException {
            return new ByteArrayInputStream(configurationSource.getBytes(Charset.defaultCharset()));
        }
    };
    return configurationFactory.build(provider, "");
}

From source file:com.duroty.application.mail.actions.InvitateToChatAction.java

/**
 * DOCUMENT ME!//from   ww w. ja v  a2  s  .c om
 *
 * @param mapping DOCUMENT ME!
 * @param form DOCUMENT ME!
 * @param request DOCUMENT ME!
 * @param response DOCUMENT ME!
 *
 * @return DOCUMENT ME!
 *
 * @throws Exception DOCUMENT ME!
 */
protected ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    ActionMessages errors = new ActionMessages();

    try {
        DynaActionForm _form = (DynaActionForm) form;

        Preferences preferencesInstance = getPreferencesInstance(request);

        PreferencesObj preferencesObj = preferencesInstance.getPreferences();

        MessageResources message = getResources(request);
        String subject = preferencesObj.getName() + " -- " + message.getMessage("chat.invite");

        String body = getEmailBody(request, preferencesObj.getLanguage());

        body = body.replaceAll("\\$\\{name\\}", preferencesObj.getName());

        Send sendInstance = getSendInstance(request);
        sendInstance.send(null, ((Integer) _form.get("identity")).intValue(), (String) _form.get("to"), null,
                null, subject, body, null, true, Charset.defaultCharset().displayName(),
                (String) _form.get("priority"));
    } catch (Exception ex) {
        String errorMessage = ExceptionUtilities.parseMessage(ex);

        if (errorMessage == null) {
            errorMessage = "NullPointerException";
        }

        errors.add("general", new ActionMessage(ExceptionCode.ERROR_MESSAGES_PREFIX + "general", errorMessage));
        request.setAttribute("exception", errorMessage);
        doTrace(request, DLog.ERROR, getClass(), errorMessage);
    } finally {
    }

    if (errors.isEmpty()) {
        doTrace(request, DLog.INFO, getClass(), "OK");

        return mapping.findForward(Constants.ACTION_SUCCESS_FORWARD);
    } else {
        saveErrors(request, errors);

        return mapping.findForward(Constants.ACTION_FAIL_FORWARD);
    }
}

From source file:de.skuzzle.polly.http.internal.HttpServerImpl.java

public HttpServerImpl(ServerFactory factory) {
    this.traffic = new TrafficInformationImpl(null);
    this.sessionHistory = new ArrayDeque<>();
    this.handlers = new URLMap<>();
    this.ipToSession = new HashMap<>();
    this.idToSession = new HashMap<>();
    this.pending = new HashMap<>();
    this.handler = new AnswerHandlerMap();
    this.factory = factory;
    this.sessionType = SESSION_TYPE_COOKIE;
    this.httpListeners = new ArrayList<>();
    this.encoding = Charset.defaultCharset().name();

    // default handler
    this.setAnswerHandler(HttpBinaryAnswer.class, new BinaryAnswerHandler());
    this.setAnswerHandler(HttpTemplateAnswer.class, new TemplateAnswerHandler());
}

From source file:com.blackducksoftware.integration.hub.detect.detector.go.DepPackager.java

private String getGopkgLockContents(final File file, final String goDepExecutable) throws IOException {
    String gopkgLockContents = null;

    final File gopkgLockFile = new File(file, "Gopkg.lock");
    if (gopkgLockFile.exists()) {
        try (FileInputStream fis = new FileInputStream(gopkgLockFile)) {
            gopkgLockContents = IOUtils.toString(fis, Charset.defaultCharset());
            logger.debug(gopkgLockContents);
        } catch (final Exception e) {
            gopkgLockContents = null;// w  ww. j  a  va 2  s .co  m
        }
        return gopkgLockContents;
    }

    // by default, we won't run 'init' and 'ensure' anymore so just return an empty string
    if (!detectConfiguration.getBooleanProperty(DetectProperty.DETECT_GO_RUN_DEP_INIT,
            PropertyAuthority.None)) {
        logger.info("Skipping Dep commands 'init' and 'ensure'");
        return "";
    }

    final File gopkgTomlFile = new File(file, "Gopkg.toml");
    final File vendorDirectory = new File(file, "vendor");
    final boolean vendorDirectoryExistedBefore = vendorDirectory.exists();
    final File vendorDirectoryBackup = new File(file, "vendor_old");
    if (vendorDirectoryExistedBefore) {
        logger.info(String.format("Backing up %s to %s", vendorDirectory.getAbsolutePath(),
                vendorDirectoryBackup.getAbsolutePath()));
        FileUtils.moveDirectory(vendorDirectory, vendorDirectoryBackup);
    }

    final String goDepInitString = String.format("%s 'init' on path %s", goDepExecutable,
            file.getAbsolutePath());
    try {
        logger.info("Running " + goDepInitString);
        final Executable executable = new Executable(file, goDepExecutable, Arrays.asList("init"));
        executableRunner.execute(executable);
    } catch (final ExecutableRunnerException e) {
        logger.error(String.format("Failed to run %s: %s", goDepInitString, e.getMessage()));
    }

    final String goDepEnsureUpdateString = String.format("%s 'ensure -update' on path %s", goDepExecutable,
            file.getAbsolutePath());
    try {
        logger.info("Running " + goDepEnsureUpdateString);
        final Executable executable = new Executable(file, goDepExecutable, Arrays.asList("ensure", "-update"));
        executableRunner.execute(executable);
    } catch (final ExecutableRunnerException e) {
        logger.error(String.format("Failed to run %s: %s", goDepEnsureUpdateString, e.getMessage()));
    }

    if (gopkgLockFile.exists()) {
        try (FileInputStream fis = new FileInputStream(gopkgLockFile)) {
            gopkgLockContents = IOUtils.toString(fis, Charset.defaultCharset());
        } catch (final Exception e) {
            gopkgLockContents = null;
        }
        gopkgLockFile.delete();
        gopkgTomlFile.delete();
        FileUtils.deleteDirectory(vendorDirectory);
        if (vendorDirectoryExistedBefore) {
            logger.info(String.format("Restoring back up %s from %s", vendorDirectory.getAbsolutePath(),
                    vendorDirectoryBackup.getAbsolutePath()));
            FileUtils.moveDirectory(vendorDirectoryBackup, vendorDirectory);
        }
    }

    return gopkgLockContents;
}

From source file:net.fabricmc.installer.installer.MultiMCInstaller.java

public static void install(File mcDir, String version, IInstallerProgress progress) throws Exception {
    File instancesDir = new File(mcDir, "instances");
    if (!instancesDir.exists()) {
        throw new FileNotFoundException(Translator.getString("install.multimc.notFound"));
    }/*from  w  ww .  j  a va  2s .co  m*/
    progress.updateProgress(Translator.getString("install.multimc.findInstances"), 10);
    String mcVer = version.split("-")[0];
    List<File> validInstances = new ArrayList<>();
    for (File instanceDir : instancesDir.listFiles()) {
        if (instanceDir.isDirectory()) {
            if (isValidInstance(instanceDir, mcVer)) {
                validInstances.add(instanceDir);
            }
        }
    }
    if (validInstances.isEmpty()) {
        throw new Exception(Translator.getString("install.multimc.noInstances").replace("[MCVER]", mcVer));
    }
    List<String> instanceNames = new ArrayList<>();
    for (File instance : validInstances) {
        instanceNames.add(instance.getName());
    }
    String instanceName = (String) JOptionPane.showInputDialog(null,
            Translator.getString("install.multimc.selectInstance"),
            Translator.getString("install.multimc.selectInstance"), JOptionPane.QUESTION_MESSAGE, null,
            instanceNames.toArray(), instanceNames.get(0));
    if (instanceName == null) {
        progress.updateProgress(Translator.getString("install.multimc.canceled"), 100);
        return;
    }
    progress.updateProgress(
            Translator.getString("install.multimc.installingInto").replace("[NAME]", instanceName), 25);
    File instnaceDir = null;
    for (File instance : validInstances) {
        if (instance.getName().equals(instanceName)) {
            instnaceDir = instance;
        }
    }
    if (instnaceDir == null) {
        throw new FileNotFoundException("Could not find " + instanceName);
    }
    File patchesDir = new File(instnaceDir, "patches");
    if (!patchesDir.exists()) {
        patchesDir.mkdir();
    }
    File fabricJar = new File(patchesDir, "Fabric-" + version + ".jar");
    if (!fabricJar.exists()) {
        progress.updateProgress(Translator.getString("install.client.downloadFabric"), 30);
        FileUtils.copyURLToFile(new URL("http://maven.modmuss50.me/net/fabricmc/fabric-base/" + version
                + "/fabric-base-" + version + ".jar"), fabricJar);
    }
    progress.updateProgress(Translator.getString("install.multimc.createJson"), 70);
    File fabricJson = new File(patchesDir, "fabric.json");
    if (fabricJson.exists()) {
        fabricJson.delete();
    }
    String json = readBaseJson();
    json = json.replaceAll("%VERSION%", version);

    ZipFile fabricZip = new ZipFile(fabricJar);
    ZipEntry dependenciesEntry = fabricZip.getEntry("dependencies.json");
    String fabricDeps = IOUtils.toString(fabricZip.getInputStream(dependenciesEntry), Charset.defaultCharset());
    json = json.replace("%DEPS%", stripDepsJson(fabricDeps.replace("\n", "")));
    FileUtils.writeStringToFile(fabricJson, json, Charset.defaultCharset());
    fabricZip.close();
    progress.updateProgress(Translator.getString("install.success"), 100);
}

From source file:com.boundary.sdk.event.snmp.SNMPEntryTest.java

@Test
public void testCopy() throws IOException, InterruptedException, CloneNotSupportedException {

    snmp_out.setMinimumExpectedMessageCount(1);
    String s = readFile("src/test/resources/snmp/snmp-entry.xml", Charset.defaultCharset());
    snmp_in.sendBody(s);/*from   ww w.j a  v  a  2 s.  co m*/
    snmp_out.assertIsSatisfied();

    List<Exchange> exchanges = snmp_out.getExchanges();
    Exchange exchange = exchanges.get(0);
    snmp snmp = exchange.getIn().getBody(snmp.class);
    snmp copy = snmp.clone();
    assertNotNull(copy);
    assertEquals("check size", snmp.getEntries().size(), copy.getEntries().size());
    assertEquals("check entry 1", snmp.getEntries().get(0), copy.getEntries().get(0));
    assertEquals("check entry 2", snmp.getEntries().get(1), copy.getEntries().get(1));

}

From source file:es.uvigo.ei.sing.jarvest.core.URLBasedTransformer.java

private String findCharset(String charset) {
    String input = charset.toUpperCase();
    if (Charset.availableCharsets().containsKey(input)) {
        return input;
    } else//from  w w  w.ja  va2s . c o  m
        return Charset.defaultCharset().name();
}

From source file:de.langmi.spring.batch.examples.readers.file.gzip.GZipBufferedReaderFactoryTest.java

@Test
public void testFailWithFileNotInGzipFormat() throws Exception {
    // adjust suffix
    gzbrf.setGzipSuffixes(new ArrayList<String>() {

        {/*from   w  w  w .  java2 s .c o m*/
            add(".txt");
        }
    });

    try {
        gzbrf.create(new FileSystemResource(PATH_TO_UNCOMPRESSED_TEST_FILE), Charset.defaultCharset().name());
        fail();
    } catch (Exception e) {
        assertTrue(e instanceof IOException);
        assertTrue(e.getMessage().contains("Not in GZIP format"));
    }
}