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

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

Introduction

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

Prototype

Charset UTF_8

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

Click Source Link

Document

Eight-bit Unicode Transformation Format.

Usage

From source file:com.vitembp.embedded.hardware.SerialBusSensorFactory.java

/**
 * Builds sensor instances for serial a bus.
 * @param bus The bus to build sensor objects for.
 * @return The set of sensors connected to the bus.
 *//* w w  w .ja  v a2  s.c o m*/
static Set<Sensor> getSerialSensors(SerialBus bus) throws IOException {
    try {
        HashSet<Sensor> toReturn = new HashSet<>();

        // query serial bus for sensor information
        bus.writeBytes(new byte[] { 'i' });
        byte[] respBytes = bus.readBytes(36);
        String resp = new String(respBytes, Charsets.UTF_8);

        if (DistanceVL53L0X.TYPE_UUID.toString().equals(resp)) {
            toReturn.add(new DistanceVL53L0X(bus));
        } else if (DistanceVL6180X.TYPE_UUID.toString().equals(resp)) {
            toReturn.add(new DistanceVL6180X(bus));
        } else if (AccelerometerFXOS8700CQSerial.TYPE_UUID.toString().equals(resp)) {
            toReturn.add(new AccelerometerFXOS8700CQSerial(bus));
        } else if (RotaryEncoderEAW0J.TYPE_UUID.toString().equals(resp)) {
            toReturn.add(new RotaryEncoderEAW0J(bus));
        } else if (AccelerometerADXL326.TYPE_UUID.toString().equals(resp)) {
            toReturn.add(new AccelerometerADXL326(bus));
        }

        return toReturn;
    } catch (IOException ex) {
        throw new IOException("Error enumerating bus: " + bus.getName(), ex);
    }
}

From source file:com.themodernway.common.util.SHA512Helper.java

@Override
public String sha512(final CharSequence text) {
    return Hex.encodeHexString(DigestUtils.getSha512Digest().digest(text.toString().getBytes(Charsets.UTF_8)));
}

From source file:com.wallellen.wechat.common.bean.WxMenu.java

/**
 * ? http://mp.weixin.qq.com/wiki/16/ff9b7b85220e1396ffa16794a9d95adc.html ?????
 *  http://mp.weixin.qq.com/wiki/13/43de8269be54a0a6f64413e4dfa94f39.html ?menu
 *
 * @param is//from   ww  w .  ja v  a  2s . c o  m
 * @return
 */
public static WxMenu fromJson(InputStream is) {
    return WxGsonBuilder.create().fromJson(new InputStreamReader(is, Charsets.UTF_8), WxMenu.class);
}

From source file:com.anrisoftware.prefdialog.csvimportdialog.panelproperties.panelproperties.CsvPanelPropertiesModule.java

@SuppressWarnings("deprecation")
@Provides/*from www.  j a  va2  s.  c  o  m*/
@Singleton
@Named("charsetDefaults")
Collection<Charset> getCharsetDefaults() {
    List<Charset> list = new ArrayList<Charset>();
    list.add(Charsets.UTF_8);
    list.add(Charsets.UTF_16);
    list.add(Charsets.UTF_16BE);
    list.add(Charsets.UTF_16LE);
    list.add(Charsets.US_ASCII);
    list.add(Charsets.ISO_8859_1);
    return list;
}

From source file:com.vitembp.services.imaging.OverlayDefinition.java

/**
 * Initializes a new instance of the OverlayDefinition class.
 * @param toBuildFrom /*from  w w w  .  j av a  2  s .c  o m*/
 */
private OverlayDefinition(String toBuildFrom) throws IOException {
    // load the definition from XML using xpath methods
    // first parse the document
    Document def;
    try {
        def = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(new ByteArrayInputStream(toBuildFrom.getBytes(Charsets.UTF_8)));
    } catch (ParserConfigurationException | SAXException | IOException ex) {
        throw new IOException("Could not parse XML input.", ex);
    }
    // prevents issues caused by parser returning multiple text elements for
    // a single text area
    def.getDocumentElement().normalize();

    // get the overlay type
    XPath xPath = XPathFactory.newInstance().newXPath();
    try {
        Node type = (Node) xPath.evaluate("/overlay/type", def, XPathConstants.NODE);
        this.overlayType = OverlayType.valueOf(type.getTextContent());
    } catch (XPathExpressionException | IllegalArgumentException ex) {
        throw new IOException("Exception parsing type.", ex);
    }

    // get element definitions
    try {
        NodeList elements = (NodeList) xPath.evaluate("/overlay/elements/element", def, XPathConstants.NODESET);

        this.elementDefinitions = new ArrayList<>();
        for (int i = 0; i < elements.getLength(); i++) {
            this.elementDefinitions.add(new ElementDefinition(elements.item(i)));
        }
    } catch (XPathExpressionException | IllegalArgumentException ex) {
        throw new IOException("Exception parsing elements.", ex);
    }
}

From source file:com.dtstack.jlogstash.distributed.http.cilent.HttpClient.java

public static String post(String url, Map<String, Object> bodyData) {
    String responseBody = null;/*from   w  w w. ja va  2  s.c  o m*/
    CloseableHttpClient httpClient = null;
    try {
        httpClient = getHttpClient();
        HttpPost httPost = new HttpPost(url);
        if (SetTimeOut) {
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(SocketTimeout)
                    .setConnectTimeout(ConnectTimeout).build();//
            httPost.setConfig(requestConfig);
        }
        if (bodyData != null && bodyData.size() > 0) {
            httPost.setEntity(new StringEntity(objectMapper.writeValueAsString(bodyData)));
        }
        //?
        CloseableHttpResponse response = httpClient.execute(httPost);
        int status = response.getStatusLine().getStatusCode();
        if (status == HttpStatus.SC_OK) {
            HttpEntity entity = response.getEntity();
            //FIXME ?header?
            responseBody = EntityUtils.toString(entity, Charsets.UTF_8);
        } else {
            logger.error("url:" + url + "--->http return status error:" + status);
        }
    } catch (Exception e) {
        logger.error("url:" + url + "--->http request error", e);
    } finally {
        try {
            if (httpClient != null)
                httpClient.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            logger.error(ExceptionUtil.getErrorMessage(e));
        }
    }
    return responseBody;
}

From source file:me.ixfan.wechatkit.util.HttpClientUtil.java

/**
 * Send HTTP POST request with body of JSON data.
 * @param url URL of request.//ww  w.  j a  va  2 s .c o m
 * @param jsonBody Body data in JSON.
 * @return JSON object of response.
 * @throws IOException If I/O error occurs.
 */
public static JsonObject sendPostRequestWithJsonBody(String url, String jsonBody) throws IOException {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpUriRequest request = RequestBuilder.post(url).setCharset(Charsets.UTF_8)
            .addHeader("Content-type", "application/json").setEntity(new StringEntity(jsonBody, Charsets.UTF_8))
            .build();
    return httpClient.execute(request, new JsonResponseHandler());
}

From source file:net.daporkchop.porkselfbot.util.HTTPUtils.java

/**
 * Performs a POST request to the specified URL and returns the result.
 * <p />//from  w w w. jav a 2s  . co m
 * The POST data will be encoded in UTF-8 as the specified contentType. The response will be parsed as UTF-8.
 * If the server returns an error but still provides a body, the body will be returned as normal.
 * If the server returns an error without any body, a relevant {@link java.io.IOException} will be thrown.
 *
 * @param url URL to submit the POST request to
 * @param post POST data in the correct format to be submitted
 * @param contentType Content type of the POST data
 * @return Raw text response from the server
 * @throws IOException The request was not successful
 */
public static String performPostRequest(final URL url, final String post, final String contentType)
        throws IOException {
    Validate.notNull(url);
    Validate.notNull(post);
    Validate.notNull(contentType);
    final HttpURLConnection connection = createUrlConnection(url);
    final byte[] postAsBytes = post.getBytes(Charsets.UTF_8);

    connection.setRequestProperty("Content-Type", contentType + "; charset=utf-8");
    connection.setRequestProperty("Content-Length", "" + postAsBytes.length);
    connection.setDoOutput(true);

    OutputStream outputStream = null;
    try {
        outputStream = connection.getOutputStream();
        IOUtils.write(postAsBytes, outputStream);
    } finally {
        IOUtils.closeQuietly(outputStream);
    }

    InputStream inputStream = null;
    try {
        inputStream = connection.getInputStream();
        final String result = IOUtils.toString(inputStream, Charsets.UTF_8);
        return result;
    } catch (final IOException e) {
        IOUtils.closeQuietly(inputStream);
        inputStream = connection.getErrorStream();

        if (inputStream != null) {
            final String result = IOUtils.toString(inputStream, Charsets.UTF_8);
            return result;
        } else {
            throw e;
        }
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}

From source file:com.difference.historybook.importer.indexer.Indexer.java

/**
 * Uploads the given HistoryRecord to the search index service
 * /*  w  w w  .  j  a v  a  2  s .  co m*/
 * @param record HistoryRecord to send to index. Should have a body.
 */
public void index(HistoryRecord record) {
    try {
        if (record.getBody() != null) {
            String url = baseUrl + "/collections/" + collection + "/"
                    + URLEncoder.encode(record.getUrl(), Charsets.UTF_8.name());
            if (record.getTimestamp() != null) {
                url = url + "/" + URLEncoder.encode(record.getTimestamp(), Charsets.UTF_8.name());
            }
            Request.Post(url).bodyString(record.getBody(), ContentType.TEXT_HTML).execute();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:aiai.ai.station.StationService.java

@PostConstruct
public void init() {
    if (!globals.isStationEnabled) {
        return;//from  ww w. j a  v  a  2s .  c om
    }

    final File file = new File(globals.stationDir, Consts.ENV_YAML_FILE_NAME);
    if (!file.exists()) {
        log.warn("Station's environment config file doesn't exist: {}", file.getPath());
        return;
    }
    try {
        env = FileUtils.readFileToString(file, Charsets.UTF_8);
        envYaml = EnvYamlUtils.toEnvYaml(env);
        if (envYaml == null) {
            log.error("env.yaml wasn't found or empty. path: {}{}env.yaml", globals.stationDir,
                    File.separatorChar);
            throw new IllegalStateException("Station isn't configured, env.yaml is empty or doesn't exist");
        }
    } catch (IOException e) {
        log.error("Error", e);
        throw new IllegalStateException("Error while loading file: " + file.getPath(), e);
    }

    final File metadataFile = new File(globals.stationDir, Consts.METADATA_YAML_FILE_NAME);
    if (!metadataFile.exists()) {
        log.warn("Station's metadata file doesn't exist: {}", file.getPath());
        return;
    }
    try (FileInputStream fis = new FileInputStream(metadataFile)) {
        metadata = MetadataUtils.to(fis);
    } catch (IOException e) {
        log.error("Error", e);
        throw new IllegalStateException("Error while loading file: " + metadataFile.getPath(), e);
    }
    //noinspection unused
    int i = 0;
}