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.wso2.is.saml.SPInitTests.java

/**
 * SAML request without signature validation turned on.
 *//* ww w.  j  a  va 2s. c o  m*/
@Test
public void testSPInitSSOWithAllConfigs() throws IdentityException {
    ServiceProviderConfig serviceProviderConfig = TestUtils
            .getServiceProviderConfigs(TestConstants.SAMPLE_ISSUER_NAME, bundleContext);
    Properties originalReqValidatorConfigs = serviceProviderConfig.getRequestValidationConfig()
            .getRequestValidatorConfigs().get(0).getProperties();
    Properties originalResponseBuilderConfigs = serviceProviderConfig.getResponseBuildingConfig()
            .getResponseBuilderConfigs().get(0).getProperties();
    try {

        applyAllConfigs(originalReqValidatorConfigs, originalResponseBuilderConfigs, serviceProviderConfig);
        AuthnRequest samlRequest = TestUtils.buildAuthnRequest("https://localhost:9292/gateway", false, false,
                TestConstants.SAMPLE_ISSUER_NAME, TestConstants.ACS_URL);
        String samlRequestString = SAML2AuthUtils.encodeForRedirect(samlRequest);
        SAML2AuthUtils.encodeForPost(SAML2AuthUtils.marshall(samlRequest));

        StringBuilder httpQueryString = new StringBuilder(
                SAML2AuthConstants.SAML_REQUEST + "=" + samlRequestString);
        httpQueryString.append("&" + SAML2AuthConstants.RELAY_STATE + "="
                + URLEncoder.encode("relayState", StandardCharsets.UTF_8.name()).trim());
        SAML2AuthUtils.addSignatureToHTTPQueryString(httpQueryString,
                SAML2AuthConstants.XML.SignatureAlgorithmURI.RSA_SHA1, SAML2AuthUtils.getServerCredentials());

        HttpURLConnection urlConnection = TestUtils.request(
                TestConstants.GATEWAY_ENDPOINT + "?" + httpQueryString.toString(), HttpMethod.GET, false);

        String content = TestUtils.getContent(urlConnection);
        String relayState = TestUtils.getParameterFromHTML(content, "'RelayState' value='", "'>");
        String fedSamlResponse = TestUtils.getSAMLResponse(false, TestConstants.CARBON_SERVER, true, true);
        fedSamlResponse = URLEncoder.encode(fedSamlResponse);
        urlConnection = TestUtils.request(TestConstants.GATEWAY_ENDPOINT, HttpMethod.POST, true);
        String postData = "SAMLResponse=" + fedSamlResponse + "&" + "RelayState=" + relayState;
        urlConnection.setDoOutput(true);
        urlConnection.getOutputStream().write(postData.toString().getBytes(Charsets.UTF_8));
        urlConnection.getResponseCode();

        String cookie = TestUtils.getResponseHeader(HttpHeaders.SET_COOKIE, urlConnection);

        cookie = cookie.split(org.wso2.carbon.identity.gateway.common.util.Constants.GATEWAY_COOKIE + "=")[1];
        Assert.assertNotNull(cookie);
        String response = TestUtils.getContent(urlConnection);
        String samlResponse = response.split("SAMLResponse' value='")[1].split("'>")[0];
        try {
            Response samlResponseObject = TestUtils.getSAMLResponse(samlResponse);
            Assert.assertTrue(samlResponseObject.getAssertions().isEmpty());
            Assert.assertNotNull(samlResponseObject.getSignature());
            Assert.assertFalse(samlResponseObject.getEncryptedAssertions().isEmpty());
        } catch (SAML2SSOServerException e) {
            log.error("Error while building response object from SAML response string", e);
        }

    } catch (IOException e) {
        Assert.fail("Error while running testSAMLAssertionWithoutRequestValidation test case");
    } finally {
        serviceProviderConfig.getRequestValidationConfig().getRequestValidatorConfigs().get(0)
                .setProperties(originalReqValidatorConfigs);
        serviceProviderConfig.getResponseBuildingConfig().getResponseBuilderConfigs().get(0)
                .setProperties(originalResponseBuilderConfigs);
    }
}

From source file:org.wso2.msf4j.deployer.MSF4JDeployerTest.java

private String getContent(HttpURLConnection urlConn) throws IOException {
    return new String(IOUtils.toByteArray(urlConn.getInputStream()), Charsets.UTF_8);
}

From source file:org.wso2.msf4j.ExtendedServiceTest.java

protected void writeContent(HttpURLConnection urlConn, String content) throws IOException {
    urlConn.getOutputStream().write(content.getBytes(Charsets.UTF_8));
}

From source file:org.wso2.msf4j.HttpServerTest.java

protected void testStreamUpload(int size, String filename) throws IOException {
    //create a random file to be uploaded.
    File fname = new File(tmpFolder, filename);
    fname.createNewFile();//from ww w .  jav a 2s .  c  o  m
    RandomAccessFile randf = new RandomAccessFile(fname, "rw");
    String contentStr = IntStream.range(0, size).mapToObj(value -> String.valueOf((int) (Math.random() * 1000)))
            .collect(Collectors.joining(""));
    randf.write(contentStr.getBytes(Charsets.UTF_8));
    randf.close();

    //test stream upload
    HttpURLConnection urlConn = request("/test/v1/stream/upload", HttpMethod.PUT);
    Files.copy(Paths.get(fname.toURI()), urlConn.getOutputStream());
    assertEquals(200, urlConn.getResponseCode());
    String contentFromServer = getContent(urlConn);
    assertEquals(contentStr, contentFromServer);
    urlConn.disconnect();
    fname.delete();
}

From source file:org.wso2.msf4j.HttpServerTest.java

@Test(timeOut = 5000)
public void testConnectionClose() throws Exception {
    URL url = baseURI.resolve("/test/v1/connectionClose").toURL();

    // Fire http request using raw socket so that we can verify the connection get closed by the server
    // after the response.
    Socket socket = createRawSocket(url);
    try {//w ww.  ja  va2 s  . c  o  m
        PrintStream printer = new PrintStream(socket.getOutputStream(), false, "UTF-8");
        printer.printf("GET %s HTTP/1.1\r\n", url.getPath());
        printer.printf("Host: %s:%d\r\n", url.getHost(), url.getPort());
        printer.print("\r\n");
        printer.flush();

        // Just read everything from the response. Since the server will close the connection, the read loop should
        // end with an EOF. Otherwise there will be timeout of this test case
        String response = IOUtils.toString(new InputStreamReader(socket.getInputStream(), Charsets.UTF_8));
        assertTrue(response.startsWith("HTTP/1.1 200 OK"));
    } finally {
        socket.close();
    }
}

From source file:org.wso2.msf4j.HttpServerTest.java

@Test
public void testUploadReject() throws Exception {
    HttpURLConnection urlConn = request("/test/v1/uploadReject", HttpMethod.POST, true);
    try {//from   w w  w  .  j  av  a2  s . c om
        urlConn.setChunkedStreamingMode(1024);
        urlConn.getOutputStream().write("Rejected Content".getBytes(Charsets.UTF_8));
        try {
            urlConn.getInputStream();
            fail();
        } catch (IOException e) {
            // Expect to get exception since server response with 400. Just drain the error stream.
            IOUtils.toByteArray(urlConn.getErrorStream());
            assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), urlConn.getResponseCode());
        }
    } finally {
        urlConn.disconnect();
    }
}

From source file:org.wso2.msf4j.HttpServerTest.java

protected String getContent(HttpURLConnection urlConn) throws IOException {
    return new String(IOUtils.toByteArray(urlConn.getInputStream()), Charsets.UTF_8);
}

From source file:org.wso2.msf4j.security.oauth2.OAuth2SecurityInterceptor.java

/**
 * Validated the given accessToken with an external key server.
 *
 * @param accessToken AccessToken to be validated.
 * @return the response from the key manager server.
 *//*w  w  w  .  jav a  2  s . c  o  m*/
private String getValidatedTokenResponse(String accessToken) throws MSF4JSecurityException {
    URL url;
    try {
        url = new URL(AUTH_SERVER_URL);
        HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
        urlConn.setDoOutput(true);
        urlConn.setRequestMethod(HttpMethod.POST);
        urlConn.getOutputStream()
                .write(("token=" + accessToken + "&token_type_hint=" + BEARER_PREFIX).getBytes(Charsets.UTF_8));
        return new String(IOUtils.toByteArray(urlConn.getInputStream()), Charsets.UTF_8);
    } catch (java.io.IOException e) {
        log.error("Error invoking Authorization Server", e);
        throw new MSF4JSecurityException(SecurityErrorCode.GENERIC_ERROR, "Error invoking Authorization Server",
                e);
    }
}

From source file:org.wso2.siddhi.extension.input.transport.http.TestUtil.java

public static HttpURLConnection writeContent(HttpURLConnection urlConn, String content) throws IOException {
    urlConn.getOutputStream().write(content.getBytes(Charsets.UTF_8));
    return urlConn;
}

From source file:rec.sys.examples.GroupLensDataModel.java

private static File convertGLFile(File originalFile) throws IOException {
    // Now translate the file; remove commas, then convert "::" delimiter to comma
    File resultFile = new File(new File(System.getProperty("java.io.tmpdir")), "ratings.txt");
    if (resultFile.exists()) {
        resultFile.delete();/*w w w.  j  ava 2 s .c om*/
    }
    try {
        Writer writer = new OutputStreamWriter(new FileOutputStream(resultFile), Charsets.UTF_8);
        for (String line : new FileLineIterable(originalFile, false)) {
            int lastDelimiterStart = line.lastIndexOf(COLON_DELIMTER);
            if (lastDelimiterStart < 0) {
                throw new IOException("Unexpected input format on line: " + line);
            }
            String subLine = line.substring(0, lastDelimiterStart);
            String convertedLine = COLON_DELIMITER_PATTERN.matcher(subLine).replaceAll(",");
            writer.write(convertedLine);
            writer.write('\n');
        }
    } catch (IOException ioe) {
        resultFile.delete();
        throw ioe;
    }
    return resultFile;
}