Example usage for org.apache.commons.io Charsets UTF_8

List of usage examples for org.apache.commons.io Charsets UTF_8

Introduction

In this page you can find the example usage for org.apache.commons.io Charsets UTF_8.

Prototype

Charset UTF_8

To view the source code for org.apache.commons.io Charsets UTF_8.

Click Source Link

Document

Eight-bit Unicode Transformation Format.

Usage

From source file:com.streamsets.pipeline.stage.origin.tcp.TestTCPServerSource.java

@Test
public void initMethod() throws Exception {

    final TCPServerSourceConfig configBean = createConfigBean(Charsets.ISO_8859_1);

    initSourceAndValidateIssues(configBean);

    // empty ports
    configBean.ports = new LinkedList<>();
    initSourceAndValidateIssues(configBean, Errors.TCP_02);

    // invalid ports
    // too large/*  w ww.  java  2 s  . c  o  m*/
    configBean.ports = Arrays.asList("123456789");
    initSourceAndValidateIssues(configBean, Errors.TCP_03);

    // not a number
    configBean.ports = Arrays.asList("abcd");
    initSourceAndValidateIssues(configBean, Errors.TCP_03);

    // start TLS config tests
    configBean.ports = randomSinglePort();
    configBean.tlsConfigBean.tlsEnabled = true;
    configBean.tlsConfigBean.keyStoreFilePath = "non-existent-file-path";
    initSourceAndValidateIssues(configBean, TlsConfigErrors.TLS_01);

    File blankTempFile = File.createTempFile("blank", "txt");
    blankTempFile.deleteOnExit();
    configBean.tlsConfigBean.keyStoreFilePath = blankTempFile.getAbsolutePath();
    initSourceAndValidateIssues(configBean, TlsConfigErrors.TLS_21);

    // now, try with real keystore
    String hostname = TLSTestUtils.getHostname();
    File testDir = new File("target", UUID.randomUUID().toString()).getAbsoluteFile();
    testDir.deleteOnExit();
    final File keyStore = new File(testDir, "keystore.jks");
    keyStore.deleteOnExit();
    Assert.assertTrue(testDir.mkdirs());
    final String keyStorePassword = "keystore";
    KeyPair keyPair = TLSTestUtils.generateKeyPair();
    Certificate cert = TLSTestUtils.generateCertificate("CN=" + hostname, keyPair, 30);
    TLSTestUtils.createKeyStore(keyStore.toString(), keyStorePassword, "web", keyPair.getPrivate(), cert);

    configBean.tlsConfigBean.keyStoreFilePath = keyStore.getAbsolutePath();
    configBean.tlsConfigBean.keyStorePassword = () -> "invalid-password";

    initSourceAndValidateIssues(configBean, TlsConfigErrors.TLS_21);

    // finally, a valid certificate/config
    configBean.tlsConfigBean.keyStorePassword = () -> keyStorePassword;
    initSourceAndValidateIssues(configBean);

    // ack ELs
    configBean.recordProcessedAckMessage = "${invalid EL)";
    initSourceAndValidateIssues(configBean, Errors.TCP_30);
    configBean.recordProcessedAckMessage = "${time:now()}";
    configBean.batchCompletedAckMessage = "${another invalid EL]";
    initSourceAndValidateIssues(configBean, Errors.TCP_31);
    configBean.batchCompletedAckMessage = "${record:value('/first')}";

    // syslog mode
    configBean.tcpMode = TCPMode.SYSLOG;
    configBean.syslogFramingMode = SyslogFramingMode.NON_TRANSPARENT_FRAMING;
    configBean.nonTransparentFramingSeparatorCharStr = "";
    initSourceAndValidateIssues(configBean, Errors.TCP_40);
    configBean.syslogFramingMode = SyslogFramingMode.OCTET_COUNTING;
    initSourceAndValidateIssues(configBean);

    // separated records
    configBean.tcpMode = TCPMode.DELIMITED_RECORDS;
    configBean.dataFormatConfig.charset = Charsets.UTF_8.name();
    initSourceAndValidateIssues(configBean, Errors.TCP_41);
    configBean.recordSeparatorStr = "";
    initSourceAndValidateIssues(configBean, Errors.TCP_40);
    configBean.recordSeparatorStr = "x";
    initSourceAndValidateIssues(configBean, DataFormatErrors.DATA_FORMAT_12);
    configBean.dataFormat = DataFormat.TEXT;
    initSourceAndValidateIssues(configBean);

}

From source file:com.zxy.commons.httpclient.HttpclientUtils.java

/**
 * Get url//  ww  w  . j  av  a2s .  c  o m
 * 
 * @param connectTimeoutSec ()
 * @param socketTimeoutSec ??()
 * @param url url?
 * @return post??
 * @throws ClientProtocolException ClientProtocolException
 * @throws IOException IOException
 */
public static String get(int connectTimeoutSec, int socketTimeoutSec, String url)
        throws ClientProtocolException, IOException {
    CloseableHttpClient httpClient = null;
    CloseableHttpResponse httpResponse = null;
    try {
        //            httpClient = HttpClients.createDefault();
        RequestConfig config = RequestConfig.custom().setConnectTimeout(connectTimeoutSec * 1000)
                .setConnectionRequestTimeout(connectTimeoutSec * 1000).setSocketTimeout(socketTimeoutSec * 1000)
                .build();
        httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();

        HttpGet httpGet = new HttpGet(url);

        httpResponse = httpClient.execute(httpGet);
        HttpEntity entity = httpResponse.getEntity();
        return EntityUtils.toString(entity, Charsets.UTF_8);
    } finally {
        HttpClientUtils.closeQuietly(httpResponse);
        HttpClientUtils.closeQuietly(httpClient);
    }
}

From source file:com.cloudbees.hudson.plugins.folder.computed.FolderComputation.java

@WithBridgeMethods(TaskListener.class)
@Nonnull//www.j  av a 2 s.co m
public synchronized StreamTaskListener createEventsListener() {
    File eventsFile = getEventsFile();
    if (!eventsFile.getParentFile().isDirectory() && !eventsFile.getParentFile().mkdirs()) {
        LOGGER.log(Level.WARNING, "Could not create directory {0} for {1}",
                new Object[] { eventsFile.getParentFile(), folder.getFullName() });
        // TODO return a StreamTaskListener sending output to a log, for now this will just try and fail to write
    }
    if (eventStreams == null) {
        eventStreams = new EventOutputStreams(new EventOutputStreams.OutputFile() {
            @NonNull
            @Override
            public File get() {
                return getEventsFile();
            }

            @Override
            public boolean canWriteNow() {
                // TODO rework once JENKINS-42248 is solved
                GregorianCalendar timestamp = new GregorianCalendar();
                timestamp.setTimeInMillis(System.currentTimeMillis() - 10000L);
                Queue.Item probe = new Queue.WaitingItem(timestamp, folder, Collections.<Action>emptyList());
                for (QueueTaskDispatcher d : QueueTaskDispatcher.all()) {
                    if (d.canRun(probe) != null) {
                        return false;
                    }
                }
                return true;
            }
        }, 250, TimeUnit.MILLISECONDS, 1024, true, EVENT_LOG_MAX_SIZE * 1024,
                BACKUP_LOG_COUNT == null ? 0 : Math.max(0, BACKUP_LOG_COUNT));
    }
    return new StreamTaskListener(eventStreams.get(), Charsets.UTF_8);
}

From source file:com.offbynull.coroutines.instrumenter.testhelpers.TestUtils.java

/**
 * Creates a JAR as a temporary file. Simple manifest file will automatically be inserted.
 *
 * @param entries files to put inside of the jar
 * @return resulting jar file/* www  . ja v a2  s . co  m*/
 * @throws IOException if any IO errors occur
 * @throws NullPointerException if any argument is {@code null} or contains {@code null} elements
 */
public static File createJar(JarEntry... entries) throws IOException {
    Validate.notNull(entries);
    Validate.noNullElements(entries);

    File tempFile = File.createTempFile(TestUtils.class.getSimpleName(), ".jar");
    tempFile.deleteOnExit();

    try (FileOutputStream fos = new FileOutputStream(tempFile);
            JarArchiveOutputStream jaos = new JarArchiveOutputStream(fos)) {
        writeJarEntry(jaos, MANIFEST_PATH, MANIFEST_TEXT.getBytes(Charsets.UTF_8));
        for (JarEntry entry : entries) {
            writeJarEntry(jaos, entry.name, entry.data);
        }
    }

    return tempFile;
}

From source file:com.github.chenxiaolong.dualbootpatcher.switcher.service.UpdateRamdiskTask.java

private boolean repatchBootImage(MbtoolInterface iface, File file, int wasType, boolean hasRomIdFile,
        UsesExfat usesExfat) throws IOException, MbtoolException {
    if (wasType == Type.LOKI || !hasRomIdFile || usesExfat != UsesExfat.UNKNOWN) {
        BootImage bi = new BootImage();
        CpioFile cpio = new CpioFile();

        try {//from w  ww  .  j a v  a 2  s.co  m
            if (!bi.load(file.getAbsolutePath())) {
                logLibMbpError(bi.getError());
                return false;
            }

            if (wasType == Type.LOKI) {
                Log.d(TAG, "Will reapply loki to boot image");
                bi.setTargetType(Type.LOKI);

                File abootFile = new File(getContext().getCacheDir() + File.separator + "aboot.img");

                // Copy aboot partition to the temporary file
                try {
                    iface.pathCopy(ABOOT_PARTITION, abootFile.getAbsolutePath());
                    iface.pathChmod(abootFile.getAbsolutePath(), 0644);
                } catch (MbtoolCommandException e) {
                    Log.e(TAG, "Failed to copy aboot partition to temporary file");
                    return false;
                }

                byte[] abootImage;
                try {
                    abootImage = org.apache.commons.io.FileUtils.readFileToByteArray(abootFile);
                } catch (IOException e) {
                    Log.e(TAG, "Failed to read temporary aboot dump", e);
                    return false;
                }
                bi.setAbootImage(abootImage);

                abootFile.delete();
            }
            if (!hasRomIdFile || usesExfat != UsesExfat.UNKNOWN) {
                if (!cpio.load(bi.getRamdiskImage())) {
                    logLibMbpError(cpio.getError());
                    return false;
                }
                if (!hasRomIdFile) {
                    cpio.remove("romid");
                    if (!cpio.addFile(mRomInfo.getId().getBytes(Charset.forName("UTF-8")), "romid", 0644)) {
                        logLibMbpError(cpio.getError());
                        return false;
                    }
                }
                if (usesExfat != UsesExfat.UNKNOWN) {
                    byte[] contents = cpio.getContents("default.prop");
                    if (contents != null) {
                        ArrayList<String> lines = new ArrayList<>();
                        for (String line : new String(contents, Charsets.UTF_8).split("\n")) {
                            if (!line.startsWith("ro.patcher.use_fuse_exfat=")) {
                                lines.add(line);
                            }
                        }
                        lines.add(
                                "ro.patcher.use_fuse_exfat=" + (usesExfat == UsesExfat.YES ? "true" : "false"));
                        cpio.setContents("default.prop",
                                StringUtils.join(lines, "\n").getBytes(Charsets.UTF_8));

                    }
                }
                bi.setRamdiskImage(cpio.createData());
            }

            if (!bi.createFile(file.getAbsolutePath())) {
                logLibMbpError(bi.getError());
                return false;
            }
        } finally {
            bi.destroy();
            cpio.destroy();
        }
    }

    return true;
}

From source file:com.nesscomputing.httpclient.factory.httpclient4.ApacheHttpClient4Factory.java

@Override
public HttpClientBodySource getHttpBodySourceFor(final Object content) {
    checkRunning();/*from   w w  w. j a v a2  s .  c  o  m*/

    if (content == null) {
        LOG.debug("No content given, returning null");
        return null;
    }

    if (content instanceof String) {
        LOG.debug("Returning String based body source.");
        return new InternalHttpBodySource(new BetterStringEntity(String.class.cast(content), Charsets.UTF_8));
    } else if (content instanceof byte[]) {
        LOG.debug("Returning byte array based body source.");
        return new InternalHttpBodySource(new ByteArrayEntity((byte[]) content));
    } else if (content instanceof InputStream) {
        LOG.debug("Returning InputStream based body source.");
        return new InternalHttpBodySource(new InputStreamEntity((InputStream) content, -1));
    }

    return null;
}

From source file:jenkins.model.RunIdMigrator.java

private void doMigrate(File dir) {
    idToNumber = new TreeMap<String, Integer>();
    File[] kids = dir.listFiles();
    // Need to process symlinks first so we can rename to them.
    List<File> kidsList = new ArrayList<File>(Arrays.asList(kids));
    Iterator<File> it = kidsList.iterator();
    while (it.hasNext()) {
        File kid = it.next();/*from ww w .  j a  va2  s  .  c o  m*/
        String name = kid.getName();
        try {
            Integer.parseInt(name);
        } catch (NumberFormatException x) {
            LOGGER.log(FINE, "ignoring nonnumeric entry {0}", name);
            continue;
        }
        try {
            if (Util.isSymlink(kid)) {
                LOGGER.log(FINE, "deleting build number symlink {0}  {1}",
                        new Object[] { name, Util.resolveSymlink(kid) });
            } else if (kid.isDirectory()) {
                LOGGER.log(FINE, "ignoring build directory {0}", name);
                continue;
            } else {
                LOGGER.log(WARNING, "need to delete anomalous file entry {0}", name);
            }
            Util.deleteFile(kid);
            it.remove();
        } catch (Exception x) {
            LOGGER.log(WARNING, "failed to process " + kid, x);
        }
    }
    it = kidsList.iterator();
    while (it.hasNext()) {
        File kid = it.next();
        try {
            String name = kid.getName();
            try {
                Integer.parseInt(name);
                LOGGER.log(FINE, "skipping new build dir {0}", name);
                continue;
            } catch (NumberFormatException x) {
                // OK, next
            }
            if (!kid.isDirectory()) {
                LOGGER.log(FINE, "skipping non-directory {0}", name);
                continue;
            }
            long timestamp;
            try {
                synchronized (legacyIdFormatter) {
                    timestamp = legacyIdFormatter.parse(name).getTime();
                }
            } catch (ParseException x) {
                LOGGER.log(WARNING, "found unexpected dir {0}", name);
                continue;
            }
            File buildXml = new File(kid, "build.xml");
            if (!buildXml.isFile()) {
                LOGGER.log(WARNING, "found no build.xml in {0}", name);
                continue;
            }
            String xml = FileUtils.readFileToString(buildXml, Charsets.UTF_8);
            Matcher m = NUMBER_ELT.matcher(xml);
            if (!m.find()) {
                LOGGER.log(WARNING, "could not find <number> in {0}/build.xml", name);
                continue;
            }
            int number = Integer.parseInt(m.group(1));
            String nl = m.group(2);
            xml = m.replaceFirst(
                    "  <id>" + name + "</id>" + nl + "  <timestamp>" + timestamp + "</timestamp>" + nl);
            File newKid = new File(dir, Integer.toString(number));
            move(kid, newKid);
            FileUtils.writeStringToFile(new File(newKid, "build.xml"), xml, Charsets.UTF_8);
            LOGGER.log(FINE, "fully processed {0}  {1}", new Object[] { name, number });
            idToNumber.put(name, number);
        } catch (Exception x) {
            LOGGER.log(WARNING, "failed to process " + kid, x);
        }
    }
}

From source file:com.cloudbees.hudson.plugins.folder.computed.FolderComputation.java

@Nonnull
public AnnotatedLargeText<FolderComputation<I>> getLogText() {
    return new AnnotatedLargeText<FolderComputation<I>>(getLogFile(), Charsets.UTF_8, !isLogUpdated(), this);
}

From source file:io.tourniquet.junit.rules.ldap.Directory.java

/**
 * Imports directory content that is defined in LDIF format and provided as input stream. The method writes the
 * stream content into a temporary file.
 *
 * @param ldifData//from   w  w w. j a  va 2  s .  c  o  m
 *         the ldif data to import as a stream
 *
 * @throws IOException
 *         if the temporary file can not be created
 */
public void importLdif(InputStream ldifData) throws IOException {

    final File ldifFile = getOuterRule().newFile("tourniquet_import.ldif");
    try (final Writer writer = new OutputStreamWriter(new FileOutputStream(ldifFile), Charsets.UTF_8)) {

        IOUtils.copy(ldifData, writer);
    }
    final String pathToLdifFile = ldifFile.getAbsolutePath();
    final CoreSession session = this.getDirectoryService().getAdminSession();
    final LdifFileLoader loader = new LdifFileLoader(session, pathToLdifFile);
    loader.execute();

}

From source file:io.inkstand.scribble.rules.ldap.Directory.java

/**
 * Imports directory content that is defined in LDIF format and provided as input stream. The method writes the
 * stream content into a temporary file.
 *
 * @param ldifData/* w w  w . j a va  2  s.  com*/
 *         the ldif data to import as a stream
 *
 * @throws IOException
 *         if the temporary file can not be created
 */
public void importLdif(InputStream ldifData) throws IOException {

    final File ldifFile = getOuterRule().newFile("scribble_import.ldif");
    try (final Writer writer = new OutputStreamWriter(new FileOutputStream(ldifFile), Charsets.UTF_8)) {

        IOUtils.copy(ldifData, writer);
    }
    final String pathToLdifFile = ldifFile.getAbsolutePath();
    final CoreSession session = this.getDirectoryService().getAdminSession();
    final LdifFileLoader loader = new LdifFileLoader(session, pathToLdifFile);
    loader.execute();

}