Example usage for org.apache.commons.lang CharEncoding UTF_8

List of usage examples for org.apache.commons.lang CharEncoding UTF_8

Introduction

In this page you can find the example usage for org.apache.commons.lang CharEncoding UTF_8.

Prototype

String UTF_8

To view the source code for org.apache.commons.lang CharEncoding UTF_8.

Click Source Link

Document

Eight-bit Unicode Transformation Format.

Usage

From source file:org.eclipse.gyrex.logback.config.internal.LogbackConfigGenerator.java

public File generateConfig() {
    // get state location
    if (!parentFolder.isDirectory() && !parentFolder.mkdirs()) {
        throw new IllegalStateException(
                String.format("Unable to create configs directory (%s).", parentFolder));
    }//from  www .j a v a  2  s .  c om

    // save file
    final File configFile = new File(parentFolder,
            String.format("logback.%s.xml", DateFormatUtils.format(lastModified, "yyyyMMdd-HHmmssSSS")));
    OutputStream outputStream = null;
    XMLStreamWriter xmlStreamWriter = null;
    try {
        outputStream = new BufferedOutputStream(FileUtils.openOutputStream(configFile));
        final XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
        xmlStreamWriter = outputFactory.createXMLStreamWriter(outputStream, CharEncoding.UTF_8);
        // try to format the output
        try {
            final Class<?> clazz = getClass().getClassLoader()
                    .loadClass("com.sun.xml.internal.txw2.output.IndentingXMLStreamWriter");
            xmlStreamWriter = (XMLStreamWriter) clazz.getConstructor(XMLStreamWriter.class)
                    .newInstance(xmlStreamWriter);
        } catch (final Exception e) {
            // ignore
        }
        config.toXml(xmlStreamWriter);
        xmlStreamWriter.flush();
    } catch (final IOException e) {
        throw new IllegalStateException(
                String.format("Unable to create config file (%s).", ExceptionUtils.getRootCauseMessage(e)), e);
    } catch (final XMLStreamException e) {
        throw new IllegalStateException(
                String.format("Error writing config (%s).", ExceptionUtils.getRootCauseMessage(e)), e);
    } finally {
        if (null != xmlStreamWriter) {
            try {
                xmlStreamWriter.close();
            } catch (final Exception e) {
                // ignore
            }
        }
        IOUtils.closeQuietly(outputStream);
    }

    // cleanup directory
    removeOldFiles(parentFolder);

    return configFile;
}

From source file:org.eclipse.gyrex.p2.internal.installer.PackageInstallState.java

public static String getActiveInstallSessionId() {
    final File sessionFile = getBaseLocation().append("sessionActive").toFile();
    installSessionIdLock.lock();//from ww w  .  j  a  v a 2s.  c o m
    try {
        return FileUtils.readFileToString(sessionFile, CharEncoding.UTF_8);
    } catch (final FileNotFoundException notFound) {
        return null;
    } catch (final IOException e) {
        throw new IllegalStateException(
                "Unable to read active install session id. " + ExceptionUtils.getRootCauseMessage(e), e);
    } finally {
        installSessionIdLock.unlock();
    }
}

From source file:org.eclipse.gyrex.p2.internal.installer.PackageInstallState.java

public static void setActiveInstallSessionId(final String activeSessionId) {
    final File sessionFile = getBaseLocation().append("sessionActive").toFile();
    installSessionIdLock.lock();/*w  w  w  .  j  a v a 2 s . c o  m*/
    try {
        FileUtils.writeStringToFile(sessionFile, activeSessionId, CharEncoding.UTF_8);
    } catch (final IOException e) {
        throw new IllegalStateException(
                "Unable to write active install session id. " + ExceptionUtils.getRootCauseMessage(e), e);
    } finally {
        installSessionIdLock.unlock();
    }
}

From source file:org.eclipse.gyrex.persistence.internal.storage.RepositoryPreferences.java

@Override
public byte[] getByteArray(final String key, final byte[] defaultValue) throws SecurityException {
    final String value = get(key, null);
    try {/*from   w ww  .  j  a v a  2s.  c o  m*/
        return value == null ? defaultValue : Base64.decodeBase64(value.getBytes(CharEncoding.UTF_8));
    } catch (final UnsupportedEncodingException e) {
        throw new IllegalStateException("Gyrex requires a platform which supports UTF-8.", e);
    }
}

From source file:org.eclipse.gyrex.persistence.internal.storage.RepositoryPreferences.java

@Override
public void putByteArray(final String key, final byte[] value, final boolean encrypt) throws SecurityException {
    try {/*from ww  w  .  j  ava2  s .  co m*/
        put(key, new String(Base64.encodeBase64(value), CharEncoding.UTF_8), encrypt);
    } catch (final UnsupportedEncodingException e) {
        throw new IllegalStateException("Gyrex requires a platform which supports UTF-8.", e);
    }
}

From source file:org.elasticsearch.discovery.custom.DataFetcher.java

public static String fetchData(String url, ESLogger logger) {
    DataInputStream responseStream = null;
    try {/*from ww w .  ja  va  2 s.co m*/
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setConnectTimeout(1000);
        conn.setReadTimeout(10000);
        conn.setRequestMethod("GET");
        if (conn.getResponseCode() != 200)
            throw new RuntimeException("Unable to get data for URL " + url);

        byte[] b = new byte[2048];
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        responseStream = new DataInputStream((FilterInputStream) conn.getContent());
        int c = 0;
        while ((c = responseStream.read(b, 0, b.length)) != -1)
            bos.write(b, 0, c);
        String return_ = new String(bos.toByteArray(), CharEncoding.UTF_8);
        logger.info(String.format("Calling URL API: %s returns: %s", url, return_));
        conn.disconnect();
        return return_;
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        try {
            if (responseStream != null)
                responseStream.close();
        } catch (Exception e) {
            logger.warn("Failed to close response stream from priam", e);
        }
    }
}

From source file:org.finra.dm.service.helper.DmJmsMessageListener.java

/**
 * Process the message as S3 notification.
 *
 * @param payload the JMS message payload.
 *
 * @return boolean whether message was processed.
 *//*  w w w . java2 s  .c om*/
private boolean processS3Notification(String payload) {
    boolean messageProcessed = false;

    try {
        // Process messages coming from S3 bucket.
        S3EventNotification s3EventNotification = S3EventNotification.parseJson(payload);
        String objectKey = URLDecoder.decode(
                s3EventNotification.getRecords().get(0).getS3().getObject().getKey(), CharEncoding.UTF_8);

        // Perform the complete upload single file.
        CompleteUploadSingleMessageResult returnValues = uploadDownloadService
                .performCompleteUploadSingleMessage(objectKey);

        LOGGER.debug(String.format(
                "completeUploadSingleMessageResult- SourceBusinessObjectDataKey: \"%s\", sourceOldStatus: \"%s\", "
                        + "sourceNewStatus: \"%s\", TargetBusinessObjectDataKey: \"%s\", targetOldStatus: \"%s\", targetNewStatus: \"%s\"",
                dmHelper.businessObjectDataKeyToString(returnValues.getSourceBusinessObjectDataKey()),
                returnValues.getSourceOldStatus(), returnValues.getSourceNewStatus(),
                dmHelper.businessObjectDataKeyToString(returnValues.getTargetBusinessObjectDataKey()),
                returnValues.getTargetOldStatus(), returnValues.getTargetNewStatus()));

        messageProcessed = true;
    } catch (Exception e) {
        LOGGER.debug(String.format(
                "Failed to process JMS message from \"%s\" queue. Payload: \"%s\" for an S3 notification.",
                DmJmsDestinationResolver.SQS_DESTINATION_DM_INCOMING, payload), e);
    }

    return messageProcessed;
}

From source file:org.gtdfree.Messages.java

public static String getString(String key) {
    if (utf8Convert == null) {
        if (RESOURCE_BUNDLE.containsKey(ENCODING)) {
            try {
                String s = RESOURCE_BUNDLE.getString(ENCODING);
                utf8Convert = s != null && CharEncoding.UTF_8.equalsIgnoreCase(s);
            } catch (MissingResourceException e) {
                // ignore
            }// ww w.  j  a  va  2s.co m
        }

        if (utf8Convert == null) {
            utf8Convert = Boolean.FALSE;
        }
    }

    try {
        String message = RESOURCE_BUNDLE.getString(key);

        if (utf8Convert) {
            try {
                // converts scrambled UTF-8 characters withing ISO_8859_1 into proper UTF-8
                message = new String(message.getBytes(CharEncoding.ISO_8859_1), CharEncoding.UTF_8);
            } catch (UnsupportedEncodingException e) {
                //e.printStackTrace();
            }
        }
        return message;
    } catch (MissingResourceException e) {
        return '!' + key + '!';
    }
}

From source file:org.intalio.tempo.workflow.wds.core.xforms.XFormsProcessor.java

/**
 * Process an XForms document./*  w  w w  .  ja  va 2 s  . com*/
 * <ul>
 * <li>If the model schema is specified as a relative URI, it is changed to comply to the form URI, 
 *     e.g. if a form is stored at (oxf:/)my/uri/form1.xform and it specified "form1.xsd" 
 *     as its model schema, then the value of the "schema" attribute of the "xforms:model" 
 *     element will be rewritten as: "oxf:/my/uri/form1.xsd"</li>
 * <li>The XForms document is reformatted in a "pretty-print" way.</li>
 * </ul>
 */
@SuppressWarnings("deprecation")
public static Item processXForm(final String itemUri, InputStream inputStream)
        throws IOException, ParserConfigurationException, SAXException {
    if (LOG.isDebugEnabled())
        LOG.debug("Processing " + itemUri);
    StringWriter out = new StringWriter();
    SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
    OutputFormat format = new OutputFormat();
    format.setEncoding(CharEncoding.UTF_8);
    format.setOmitXMLDeclaration(false);
    format.setOmitComments(false);
    format.setPreserveSpace(true);
    SchemaURLRewriter ser = new SchemaURLRewriter(out, format, itemUri);
    XMLReader reader = parser.getXMLReader();
    reader.setContentHandler(ser);
    reader.parse(new InputSource(inputStream));
    return new Item(itemUri, XFORMS_CONTENT_TYPE, out.toString().getBytes(CharEncoding.UTF_8));
}

From source file:org.jenkinsci.plugins.exportparams.ExportParametersBuilder.java

@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
        throws InterruptedException, IOException {
    if (StringUtils.isNotEmpty(filePath)) {
        String path;/*w ww.  j  a v a2s  .c om*/
        if (filePath.endsWith(".")) {
            path = filePath.substring(0, filePath.length() - 1);
        } else {
            path = filePath + "." + fileFormat;
        }

        FilePath paramFile = new FilePath(build.getWorkspace(), path);
        Filter filter = FilterFactory.createFilter(keyPattern, useRegexp);
        EnvVars env = filter.apply(build);

        Serializer serializer = SerializerFactory.createSerializer(fileFormat);
        if (serializer != null) {
            String buf = serializer.serialize(env);
            if (buf != null) {
                try {
                    paramFile.delete();
                    paramFile.write(buf, CharEncoding.UTF_8);
                    listener.getLogger().println("Stored the below parameters into " + paramFile.getRemote());
                    for (String key : env.keySet()) {
                        listener.getLogger().println(key);
                    }
                    build.addAction(createParametersAction(paramFile.getRemote(), fileFormat));
                } catch (Exception ex) {
                    listener.getLogger().println("Could not store parameters into " + paramFile.getRemote());
                }
            }
        }
    }
    return true;
}