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:org.settings4j.connector.JNDIConnectorTest.java

@Test
public void testJNDIConnectorWithJNDI() throws Exception {
    LOG.info("START: testJNDIConnectorWithJNDI");
    // Set JNDI Tomcat Configs
    setTomcatJNDIContextProperties();//from w  ww  .  j  a  v  a2 s .c o m

    final String testTextPath = this.testDir.getAbsolutePath() + "/test.txt";

    JNDIConnector connector;
    int saveStatus;
    String resultString;
    byte[] resultContent;
    Object resultObject;

    connector = new JNDIConnector();

    resultString = connector.getString("helloWorldPath");
    assertThat(resultString, is(nullValue()));

    resultContent = connector.getContent("helloWorldPath");
    assertThat(resultContent, is(nullValue()));

    resultObject = connector.getObject("helloWorldPath");
    assertThat(resultObject, is(nullValue()));

    // set the PATH into the JNDI-Context
    saveStatus = connector.setObject("helloWorldPath", testTextPath);
    assertThat(saveStatus, is(Constants.SETTING_SUCCESS));
    resultString = connector.getString("helloWorldPath");
    assertThat(resultString, is(testTextPath));

    // if no ContentResolver is available. the value will be stored directly into the JNDI-Context
    saveStatus = connector.setObject("helloWorldPath", "Hello World".getBytes(this.charset));
    assertThat(saveStatus, is(Constants.SETTING_SUCCESS));
    // The String-Value cannot read a byte[]
    resultString = connector.getString("helloWorldPath");
    assertThat(resultString, is(nullValue()));
    // The Content-Value should be the same
    resultContent = connector.getContent("helloWorldPath");
    assertThat(resultContent, is(notNullValue()));
    assertThat(new String(resultContent, this.charset), is("Hello World"));

    // No Exception if JNDIContext not available
    saveStatus = connector.setObject("helloWorldPath", testTextPath);
    assertThat(saveStatus, is(Constants.SETTING_SUCCESS));
    resultString = connector.getString("helloWorldPath");
    assertThat(resultString, is(testTextPath));
    resultObject = connector.getObject("helloWorldPath");
    assertThat(resultObject, is((Object) testTextPath));

    // if no ObjectResolver is available. the value will be stored directly into the JNDI-Context
    final ContentResolver contentResolver = new UnionContentResolver();
    final FSContentResolver fsContentResolver = new FSContentResolver();
    fsContentResolver.setRootFolderPath(this.testDir.getAbsolutePath()); // should also work with temp-folder
    contentResolver.addContentResolver(fsContentResolver);
    contentResolver.addContentResolver(new ClasspathContentResolver());
    connector.setContentResolver(contentResolver);

    // set the PATH into the JNDI-Context
    saveStatus = connector.setObject("helloWorldPath", testTextPath);
    assertThat(saveStatus, is(Constants.SETTING_SUCCESS));
    resultString = connector.getString("helloWorldPath");
    assertThat(resultString, is(testTextPath));

    // Store the content into the file on the file system.
    // And save the Path in the JNDI Context.
    FileUtils.writeStringToFile(new File(testTextPath), "Hello World FileContent", Charsets.UTF_8);
    saveStatus = connector.setObject("helloWorldPath", testTextPath);

    assertThat(saveStatus, is(Constants.SETTING_SUCCESS));
    // The String-Value should be the text-File Path.
    resultString = connector.getString("helloWorldPath");
    assertThat(resultString, is(testTextPath));
    // The Content-Value should be content of the file.
    resultContent = connector.getContent("helloWorldPath");
    assertThat(resultContent, is(notNullValue()));
    assertThat(new String(resultContent, this.charset), is("Hello World FileContent"));

}

From source file:org.silverpeas.core.io.temp.TemporaryWorkspaceTranslation.java

/**
 * Centralizes the initialization.//from  w w w  .j  a  v  a2  s  .  c  om
 */
private void initialize() {
    synchronized (lock) {
        if (descriptor.isFile() && descriptor.length() > 30) {
            try {
                for (String line : FileUtils.readLines(this.descriptor, Charsets.UTF_8)) {
                    int splitIndex = line.indexOf('=');
                    if (splitIndex > 0) {
                        descriptorContent.put(line.substring(0, splitIndex), line.substring(splitIndex + 1));
                    }
                }
            } catch (IOException e) {
                throw new SilverpeasRuntimeException(e);
            }
        } else {
            descriptorContent.put(TRANSLATION_ID, UUID.randomUUID().toString());
        }
        this.workspace = new File(FileRepositoryManager.getTemporaryPath(),
                descriptorContent.get(TRANSLATION_ID));
    }
}

From source file:org.silverpeas.core.io.temp.TemporaryWorkspaceTranslation.java

/**
 * Saves on filesystem the descriptor content.
 *///  ww  w. j a  v a 2 s.c  o  m
private void saveDescriptor() {
    synchronized (lock) {
        try {
            if (descriptorContent.containsKey(TRANSLATION_ID)) {
                StringBuilder content = new StringBuilder();
                for (Map.Entry<String, String> line : descriptorContent.entrySet()) {
                    if (content.length() > 0) {
                        content.append("\n");
                    }
                    content.append(line.getKey()).append("=").append(line.getValue());
                }
                FileUtils.writeStringToFile(descriptor, content.toString(), Charsets.UTF_8);
            }
        } catch (IOException e) {
            SilverLogger.getLogger(this).silent(e);
        }
    }
}

From source file:org.silverpeas.core.notification.user.delayed.delegate.DelayedNotificationDelegateIT.java

private DelayedNotificationDelegateStub assertDelayedNotifications(final Date date, final int[] userIds,
        final String language) throws Exception {

    for (final Integer userId : userIds) {
        final Map<NotifChannel, List<DelayedNotificationData>> dndMap = DelayedNotificationProvider
                .getDelayedNotification().findDelayedNotificationByUserIdGroupByChannel(userId,
                        DelayedNotificationProvider.getDelayedNotification().getWiredChannels());
        for (final List<DelayedNotificationData> dndList : dndMap.values()) {
            for (final DelayedNotificationData dnd : dndList) {
                dnd.setLanguage(language);
                DelayedNotificationProvider.getDelayedNotification().saveDelayedNotification(dnd);
            }/*from   w w w. jav a2  s.com*/
        }
    }

    final DelayedNotificationDelegateStub stub = new DelayedNotificationDelegateStub();
    stub.performDelayedNotificationsSending(date, getAimedChannelsBase());
    assertThat(stub.sendedList.size(), is(userIds.length));
    for (int i = 0; i < userIds.length; i++) {
        try (InputStream expected = DelayedNotificationDelegateIT.class.getClassLoader()
                .getResourceAsStream("org/silverpeas/core/notification/user/delayed/result-synthese-"
                        + userIds[i] + "-" + language + ".txt")) {
            String expectedNotif = IOUtils.toString(expected, Charsets.UTF_8).replaceAll("[\r\n\t]", "");
            String actualNotif = stub.sendedList.get(i).getMessage().replaceAll("[\r\n\t]", "");
            assertThat(actualNotif, is(expectedNotif));
        }
    }
    return stub;
}

From source file:org.silverpeas.core.test.rule.DbSetupRule.java

@SuppressWarnings("ConstantConditions")
private Operation loadOperationFromSqlScripts(Class classOfTest, String[] scripts) {
    List<Operation> statements = new ArrayList<>();
    if (scripts != null) {
        for (final String script : scripts) {
            if (FilenameUtils.getExtension(script).toLowerCase().equals("sql")) {
                try (InputStream sqlScriptInput = classOfTest.getResourceAsStream(script)) {
                    if (sqlScriptInput != null) {
                        StringWriter sqlScriptContent = new StringWriter();
                        IOUtils.copy(sqlScriptInput, sqlScriptContent, Charsets.UTF_8);
                        if (sqlScriptContent.toString() != null && !sqlScriptContent.toString().isEmpty()) {
                            String[] sql = sqlScriptContent.toString().split(";");
                            //prepareCleanUpOperation(sql);
                            statements.add(Operations.sql(sql));
                        }/* w  ww . j a  v  a 2s.c om*/
                    }
                } catch (IOException e) {
                    Logger.getLogger(getClass().getSimpleName()).log(Level.SEVERE,
                            "Error while loading the SQL script {0}!", script);
                }
            }
        }
    }
    return Operations.sequenceOf(statements);
}

From source file:org.silverpeas.dbbuilder.DBBuilder.java

private static DBXmlDocument loadMasterContribution(File dirXml) throws IOException, AppBuilderException {
    DBXmlDocument destXml = new DBXmlDocument(dirXml, MASTER_DBCONTRIBUTION_FILE);
    destXml.setOutputEncoding(CharEncoding.UTF_8);
    if (!destXml.getPath().exists()) {
        destXml.getPath().createNewFile();
        BufferedWriter destXmlOut = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(destXml.getPath(), false), Charsets.UTF_8));
        try {//w  ww. j a v  a  2s  .  co m
            destXmlOut.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            destXmlOut.newLine();
            destXmlOut.write("<allcontributions>");
            destXmlOut.newLine();
            destXmlOut.write("</allcontributions>");
            destXmlOut.newLine();
            destXmlOut.flush();
        } finally {
            IOUtils.closeQuietly(destXmlOut);
        }
    }
    destXml.load();
    return destXml;
}

From source file:org.silverpeas.dbbuilder.DBBuilderFileItemTest.java

@Test
public void testMergeInstallation() throws Exception {
    DBXmlDocument destXml = new DBXmlDocument();
    ByteArrayInputStream input = new ByteArrayInputStream(
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<allcontributions>\n</allcontributions>\n"
                    .getBytes(Charsets.UTF_8));
    destXml.loadFrom(input);//w w w .  ja  v a  2  s  .co m
    destXml.setOutputEncoding(CharEncoding.UTF_8);
    DBXmlDocument doc = new DBXmlDocument();
    doc.loadFrom(
            this.getClass().getClassLoader().getResourceAsStream("contribution/versioning-contribution.xml"));
    DBBuilderFileItem instance = new DBBuilderFileItem(doc);
    destXml.mergeWith(instance, DBBuilder.TAGS_TO_MERGE_4_INSTALL,
            Collections.singletonList(new VersionTag(CURRENT_TAG, instance.getVersionFromFile())));
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    destXml.saveTo(out);
    assertThat(out.toString(CharEncoding.UTF_8), is("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n"
            + "<allcontributions>\r\n" + "    <module id=\"versioning\" version=\"012\">\r\n"
            + "        <create_table>\r\n"
            + "            <file name=\"postgres\\versioning\\012\\create_table.sql\" type=\"sqlstatementlist\" delimiter=\";\" keepdelimiter=\"NO\" />\r\n"
            + "        </create_table>\r\n" + "    </module>\r\n" + "</allcontributions>\r\n\r\n"));
}

From source file:org.silverpeas.dbbuilder.DBBuilderFileItemTest.java

@Test
public void testMergeUpdate() throws Exception {
    DBXmlDocument destXml = new DBXmlDocument();
    ByteArrayInputStream input = new ByteArrayInputStream(
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<allcontributions>\n</allcontributions>\n"
                    .getBytes(Charsets.UTF_8));
    destXml.loadFrom(input);// ww w.  j  a  v a  2s. c  o  m
    destXml.setOutputEncoding(CharEncoding.UTF_8);
    DBXmlDocument doc = new DBXmlDocument();
    doc.loadFrom(
            this.getClass().getClassLoader().getResourceAsStream("contribution/versioning-contribution.xml"));
    DBBuilderFileItem instance = new DBBuilderFileItem(doc);
    List<VersionTag> blocks_merge = new ArrayList<VersionTag>();
    int iversionDB = 9;
    int versionFile = Integer.parseInt(instance.getVersionFromFile());
    for (int i = 0; i < versionFile - iversionDB; i++) {
        String sversionFile = "000" + (iversionDB + i);
        sversionFile = sversionFile.substring(sversionFile.length() - 3);
        blocks_merge.add(new VersionTag(PREVIOUS_TAG, sversionFile));
    }
    destXml.mergeWith(instance, DBBuilder.TAGS_TO_MERGE_4_INSTALL, blocks_merge);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    destXml.saveTo(out);
    assertThat(out.toString(CharEncoding.UTF_8), is("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n"
            + "<allcontributions>\r\n" + "    <module id=\"versioning\" version=\"010\">\r\n"
            + "        <create_table>\r\n"
            + "            <file name=\"postgres\\versioning\\up009\\alter_table.sql\" type=\"sqlstatementlist\" delimiter=\";\" keepdelimiter=\"NO\" />\r\n"
            + "        </create_table>\r\n" + "    </module>\r\n"
            + "    <module id=\"versioning\" version=\"011\">\r\n" + "        <create_table>\r\n"
            + "            <file name=\"postgres\\versioning\\up010\\create_table.sql\" type=\"sqlstatementlist\" delimiter=\";\" keepdelimiter=\"NO\" />\r\n"
            + "        </create_table>\r\n" + "    </module>\r\n"
            + "    <module id=\"versioning\" version=\"012\">\r\n" + "        <create_table>\r\n"
            + "            <file name=\"VersioningMigrator.jar\" type=\"javalib\" classname=\"org.silverpeas.migration.jcr.version.VersioningMigrator\" methodname=\"migrateDocuments\" />\r\n"
            + "        </create_table>\r\n" + "    </module>\r\n" + "</allcontributions>\r\n\r\n"));
}

From source file:org.silverpeas.dbbuilder.DBBuilderPiece.java

public DBBuilderPiece(Console console, String pieceName, String actionName, boolean traceMode)
        throws Exception {
    this.console = console;
    this.traceMode = traceMode;
    this.actionName = actionName;
    this.pieceName = pieceName;
    if (pieceName.endsWith(".jar")) {
        content = "";
    } else {//ww  w  . j  a  v a 2 s  .c o  m
        // charge son contenu sauf pour un jar qui doit tre dans le classpath
        File myFile = new File(pieceName);
        if (!myFile.exists() || !myFile.isFile() || !myFile.canRead()) {
            console.printMessage("\t\t***Unable to load : " + pieceName);
            throw new Exception("Unable to find or load : " + pieceName);
        }
        int fileSize = (int) myFile.length();
        byte[] data = new byte[fileSize];
        DataInputStream in = new DataInputStream(new FileInputStream(pieceName));
        try {
            in.readFully(data);
        } finally {
            IOUtils.closeQuietly(in);
        }
        content = new String(data, Charsets.UTF_8);
    }
    Properties res = DBBuilder.getdbBuilderResources();
    if (res != null) {
        for (Enumeration e = res.keys(); e.hasMoreElements();) {
            String key = (String) e.nextElement();
            String value = res.getProperty(key);
            content = StringUtil.sReplace("${" + key + '}', value, content);
        }
    }
}

From source file:org.silverpeas.migration.jcr.service.repository.DocumentRepositoryTest.java

/**
 * Test of createDocument method, of class DocumentRepository.
 *//*  www .j  a  va 2  s.  c  om*/
@Test
public void testCreateDocument() throws Exception {
    new JcrDocumentRepositoryTest() {
        @Override
        public void run(final Session session) throws Exception {
            String foreignId = "node18";
            InputStream content = new ByteArrayInputStream("This is a test".getBytes(Charsets.UTF_8));
            SimpleAttachment attachment = defaultENContentBuilder().build();
            Date creationDate = attachment.getCreated();
            SimpleDocument document = defaultDocumentBuilder(foreignId, attachment).build();
            SimpleDocumentPK result = getDocumentRepository().createDocument(session, document);
            getDocumentRepository().storeContent(document, content);
            SimpleDocumentPK expResult = new SimpleDocumentPK(result.getId(), instanceId);
            assertThat(result, is(expResult));
            SimpleDocument doc = getDocumentRepository().findDocumentById(session, expResult, "en");
            assertThat(doc, is(notNullValue()));
            assertThat(doc.getOldSilverpeasId(), greaterThan(0L));
            assertThat(doc.getCreated(), is(creationDate));
            checkEnglishSimpleDocument(doc);
        }
    }.execute();
}