Example usage for java.nio.charset StandardCharsets ISO_8859_1

List of usage examples for java.nio.charset StandardCharsets ISO_8859_1

Introduction

In this page you can find the example usage for java.nio.charset StandardCharsets ISO_8859_1.

Prototype

Charset ISO_8859_1

To view the source code for java.nio.charset StandardCharsets ISO_8859_1.

Click Source Link

Document

ISO Latin Alphabet No.

Usage

From source file:org.parosproxy.paros.network.HttpBody.java

/**
 * Gets the {@code Charset} that should be used internally by the class for {@code String} related operations.
 * <p>//from   w w  w  .j  av a 2 s  .c o m
 * If no {@code Charset} was set (that is, is {@code null}) it falls back to {@code ISO-8859-1}, otherwise it returns the
 * {@code Charset} set.
 * 
 * @return the {@code Charset} to be used for {@code String} related operations, never {@code null}
 * @see #DEFAULT_CHARSET
 * @see #setCharset(String)
 */
private Charset getCharsetImpl() {
    if (charset != null) {
        return charset;
    }
    return StandardCharsets.ISO_8859_1;
}

From source file:com.jayway.restassured.itest.java.ContentTypeITest.java

@Test
public void encoder_config_can_specify_a_default_charset_for_a_specific_content_type_using_enum() {
    given().config(config().encoderConfig(encoderConfig()
            .defaultCharsetForContentType(StandardCharsets.ISO_8859_1.toString(), ContentType.JSON)))
            .contentType(ContentType.JSON).when().post("/returnContentTypeAsBody").then()
            .body(equalTo(ContentType.JSON.withCharset(StandardCharsets.ISO_8859_1.toString())));
}

From source file:io.restassured.itest.java.ContentTypeITest.java

@Test
public void encoder_config_can_specify_a_default_charset_for_a_specific_content_type_using_enum() {
    given().config(config().encoderConfig(EncoderConfig.encoderConfig()
            .defaultCharsetForContentType(StandardCharsets.ISO_8859_1.toString(), ContentType.JSON)))
            .contentType(ContentType.JSON).when().post("/returnContentTypeAsBody").then()
            .body(equalTo(ContentType.JSON.withCharset(StandardCharsets.ISO_8859_1.toString())));
}

From source file:com.jayway.restassured.itest.java.ContentTypeITest.java

@Test
public void encoder_config_can_specify_a_default_charset_for_a_specific_content_type_using_string() {
    given().config(config().encoderConfig(encoderConfig()
            .defaultCharsetForContentType(StandardCharsets.ISO_8859_1.toString(), "application/json")))
            .contentType(ContentType.JSON).when().post("/returnContentTypeAsBody").then()
            .body(equalTo(ContentType.JSON.withCharset(StandardCharsets.ISO_8859_1.toString())));
}

From source file:io.restassured.itest.java.ContentTypeITest.java

@Test
public void encoder_config_can_specify_a_default_charset_for_a_specific_content_type_using_string() {
    given().config(config().encoderConfig(EncoderConfig.encoderConfig()
            .defaultCharsetForContentType(StandardCharsets.ISO_8859_1.toString(), "application/json")))
            .contentType(ContentType.JSON).when().post("/returnContentTypeAsBody").then()
            .body(equalTo(ContentType.JSON.withCharset(StandardCharsets.ISO_8859_1.toString())));
}

From source file:com.evolveum.midpoint.notifications.impl.api.transports.SimpleSmsTransport.java

@Override
public void send(Message message, String transportName, Event event, Task task, OperationResult parentResult) {

    OperationResult result = parentResult.createSubresult(DOT_CLASS + "send");
    result.addArbitraryObjectCollectionAsParam("message recipient(s)", message.getTo());
    result.addParam("message subject", message.getSubject());

    SystemConfigurationType systemConfiguration = NotificationFunctionsImpl
            .getSystemConfiguration(cacheRepositoryService, result);
    if (systemConfiguration == null || systemConfiguration.getNotificationConfiguration() == null) {
        String msg = "No notifications are configured. SMS notification to " + message.getTo()
                + " will not be sent.";
        LOGGER.warn(msg);//from   ww  w . ja va 2 s  .co m
        result.recordWarning(msg);
        return;
    }

    String smsConfigName = StringUtils.substringAfter(transportName, NAME + ":");
    SmsConfigurationType found = null;
    for (SmsConfigurationType smsConfigurationType : systemConfiguration.getNotificationConfiguration()
            .getSms()) {
        if (StringUtils.isEmpty(smsConfigName) && smsConfigurationType.getName() == null
                || StringUtils.isNotEmpty(smsConfigName)
                        && smsConfigName.equals(smsConfigurationType.getName())) {
            found = smsConfigurationType;
            break;
        }
    }

    if (found == null) {
        String msg = "SMS configuration '" + smsConfigName + "' not found. SMS notification to "
                + message.getTo() + " will not be sent.";
        LOGGER.warn(msg);
        result.recordWarning(msg);
        return;
    }

    SmsConfigurationType smsConfigurationType = found;
    String logToFile = smsConfigurationType.getLogToFile();
    if (logToFile != null) {
        TransportUtil.logToFile(logToFile, TransportUtil.formatToFileNew(message, transportName), LOGGER);
    }
    String file = smsConfigurationType.getRedirectToFile();
    if (file != null) {
        writeToFile(message, file, null, emptyList(), null, result);
        return;
    }

    if (smsConfigurationType.getGateway().isEmpty()) {
        String msg = "SMS gateway(s) are not defined, notification to " + message.getTo()
                + " will not be sent.";
        LOGGER.warn(msg);
        result.recordWarning(msg);
        return;
    }

    String from;
    if (message.getFrom() != null) {
        from = message.getFrom();
    } else if (smsConfigurationType.getDefaultFrom() != null) {
        from = smsConfigurationType.getDefaultFrom();
    } else {
        from = "";
    }

    if (message.getTo().isEmpty()) {
        String msg = "There is no recipient to send the notification to.";
        LOGGER.warn(msg);
        result.recordWarning(msg);
        return;
    }

    List<String> to = message.getTo();
    assert to.size() > 0;

    for (SmsGatewayConfigurationType smsGatewayConfigurationType : smsConfigurationType.getGateway()) {
        OperationResult resultForGateway = result.createSubresult(DOT_CLASS + "send.forGateway");
        resultForGateway.addContext("gateway name", smsGatewayConfigurationType.getName());
        try {
            ExpressionVariables variables = getDefaultVariables(from, to, message);
            HttpMethodType method = defaultIfNull(smsGatewayConfigurationType.getMethod(), HttpMethodType.GET);
            ExpressionType urlExpression = defaultIfNull(smsGatewayConfigurationType.getUrlExpression(),
                    smsGatewayConfigurationType.getUrl());
            String url = evaluateExpressionChecked(urlExpression, variables, "sms gateway request url", task,
                    result);
            LOGGER.debug("Sending SMS to URL {} (method {})", url, method);
            if (url == null) {
                throw new IllegalArgumentException("No URL specified");
            }

            List<String> headersList = evaluateExpressionsChecked(
                    smsGatewayConfigurationType.getHeadersExpression(), variables,
                    "sms gateway request headers", task, result);
            LOGGER.debug("Using request headers:\n{}", headersList);

            String encoding = defaultIfNull(smsGatewayConfigurationType.getBodyEncoding(),
                    StandardCharsets.ISO_8859_1.name());
            String body = evaluateExpressionChecked(smsGatewayConfigurationType.getBodyExpression(), variables,
                    "sms gateway request body", task, result);
            LOGGER.debug("Using request body text (encoding: {}):\n{}", encoding, body);

            if (smsGatewayConfigurationType.getLogToFile() != null) {
                TransportUtil.logToFile(smsGatewayConfigurationType.getLogToFile(),
                        formatToFile(message, url, headersList, body), LOGGER);
            }
            if (smsGatewayConfigurationType.getRedirectToFile() != null) {
                writeToFile(message, smsGatewayConfigurationType.getRedirectToFile(), url, headersList, body,
                        resultForGateway);
                result.computeStatus();
                return;
            } else {
                HttpClientBuilder builder = HttpClientBuilder.create();
                String username = smsGatewayConfigurationType.getUsername();
                ProtectedStringType password = smsGatewayConfigurationType.getPassword();
                if (username != null) {
                    CredentialsProvider provider = new BasicCredentialsProvider();
                    String plainPassword = password != null ? protector.decryptString(password) : null;
                    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username,
                            plainPassword);
                    provider.setCredentials(AuthScope.ANY, credentials);
                    builder = builder.setDefaultCredentialsProvider(provider);
                }
                HttpClient client = builder.build();
                HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(
                        client);
                ClientHttpRequest request = requestFactory.createRequest(new URI(url),
                        HttpUtil.toHttpMethod(method));
                setHeaders(request, headersList);
                if (body != null) {
                    request.getBody().write(body.getBytes(encoding));
                }
                ClientHttpResponse response = request.execute();
                LOGGER.debug("Result: " + response.getStatusCode() + "/" + response.getStatusText());
                if (response.getStatusCode().series() != HttpStatus.Series.SUCCESSFUL) {
                    throw new SystemException("SMS gateway communication failed: " + response.getStatusCode()
                            + ": " + response.getStatusText());
                }
                LOGGER.info("Message sent successfully to {} via gateway {}.", message.getTo(),
                        smsGatewayConfigurationType.getName());
                resultForGateway.recordSuccess();
                result.recordSuccess();
                return;
            }
        } catch (Throwable t) {
            String msg = "Couldn't send SMS to " + message.getTo() + " via "
                    + smsGatewayConfigurationType.getName() + ", trying another gateway, if there is any";
            LoggingUtils.logException(LOGGER, msg, t);
            resultForGateway.recordFatalError(msg, t);
        }
    }
    LOGGER.warn("No more SMS gateways to try, notification to " + message.getTo() + " will not be sent.");
    result.recordWarning("Notification to " + message.getTo() + " could not be sent.");
}

From source file:com.daneshzaki.tumblej.TumbleJ.java

/**
 * This method writes audio posts to the Tumblr tumblog.
 * Only MP3 format is supported by Tumblr as of August 13, 2011.
 * //from w w  w  .j  a  v a  2 s  .com
 * @param data An MP3 audio file (max 5 MB).
 * @param caption caption for the audio file
 * @param tags tags for the post
 * @param date date of the post
 * @return API Response.
 */
public JSONObject postAudioData(byte[] data, String caption, String tags, String date) throws Exception {
    Map<String, Object> params = new HashMap<String, Object>();
    String dataStr = IOUtils.toString(data, StandardCharsets.ISO_8859_1.name()); // TODO: huh?
    params.put("data", dataStr);
    if (caption != null && caption != "")
        params.put("source", caption);
    return post(POST_AUDIO, tags, date, params);
}

From source file:org.omegat.util.WikiGet.java

private static void addProxyAuthentication(HttpURLConnection conn) {
    // Added to pass through authenticated proxy
    String encodedUser = Preferences.getPreference(Preferences.PROXY_USER_NAME);
    if (!StringUtil.isEmpty(encodedUser)) { // There is a proxy user
        String encodedPassword = Preferences.getPreference(Preferences.PROXY_PASSWORD);
        try {/*from w w w .  j a v  a 2  s  . co  m*/
            String userPass = StringUtil.decodeBase64(encodedUser, StandardCharsets.ISO_8859_1) + ":"
                    + StringUtil.decodeBase64(encodedPassword, StandardCharsets.ISO_8859_1);
            String encodedUserPass = Base64.getMimeEncoder()
                    .encodeToString(userPass.getBytes(StandardCharsets.ISO_8859_1));
            conn.setRequestProperty("Proxy-Authorization", "Basic " + encodedUserPass);
        } catch (IllegalArgumentException ex) {
            Log.logErrorRB("LOG_DECODING_ERROR");
            Log.log(ex);
        }
    }
}

From source file:org.openhab.binding.robonect.internal.RobonectClient.java

private String sendCommand(Command command) {
    try {/*from   ww  w .  ja  v  a2 s.  c om*/
        if (logger.isDebugEnabled()) {
            logger.debug("send HTTP GET to: {} ", command.toCommandURL(baseUrl));
        }
        ContentResponse response = httpClient.newRequest(command.toCommandURL(baseUrl)).method(HttpMethod.GET)
                .timeout(30000, TimeUnit.MILLISECONDS).send();
        String responseString = null;

        // jetty uses UTF-8 as default encoding. However, HTTP 1.1 specifies ISO_8859_1
        if (StringUtils.isBlank(response.getEncoding())) {
            responseString = new String(response.getContent(), StandardCharsets.ISO_8859_1);
        } else {
            // currently v0.9e Robonect does not specifiy the encoding. But if later versions will
            // add, it should work with the default method to get the content as string.
            responseString = response.getContentAsString();
        }

        if (logger.isDebugEnabled()) {
            logger.debug("Response body was: {} ", responseString);
        }
        return responseString;
    } catch (ExecutionException | TimeoutException | InterruptedException e) {
        throw new RobonectCommunicationException("Could not send command " + command.toCommandURL(baseUrl), e);
    }
}

From source file:org.sejda.sambox.pdmodel.encryption.SecurityHandler.java

/**
 * This will decrypt a stream./*from ww  w .  j  ava2 s  .  c o m*/
 *
 * @param stream The stream to decrypt.
 * @param objNum The object number.
 * @param genNum The object generation number.
 *
 * @throws IOException If there is an error getting the stream data.
 */
public void decryptStream(COSStream stream, long objNum, long genNum) throws IOException {
    COSBase type = stream.getCOSName(COSName.TYPE);
    if (!decryptMetadata && COSName.METADATA.equals(type)) {
        return;
    }
    // "The cross-reference stream shall not be encrypted"
    if (COSName.XREF.equals(type)) {
        return;
    }
    if (COSName.METADATA.equals(type)) {
        byte buf[] = new byte[10];
        // PDFBOX-3229 check case where metadata is not encrypted despite /EncryptMetadata missing
        try (InputStream is = stream.getUnfilteredStream()) {
            is.read(buf);
        }
        if (Arrays.equals(buf, "<?xpacket ".getBytes(StandardCharsets.ISO_8859_1))) {
            LOG.warn("Metadata is not encrypted, but was expected to be");
            LOG.warn("Read PDF specification about EncryptMetadata (default value: true)");
            return;
        }
    }
    decryptDictionary(stream, objNum, genNum);
    byte[] encrypted = IOUtils.toByteArray(stream.getFilteredStream());
    ByteArrayInputStream encryptedStream = new ByteArrayInputStream(encrypted);
    try (OutputStream output = stream.createFilteredStream()) {
        decryptData(objNum, genNum, encryptedStream, output);
    }
}