Example usage for java.nio.charset StandardCharsets UTF_8

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

Introduction

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

Prototype

Charset UTF_8

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

Click Source Link

Document

Eight-bit UCS Transformation Format.

Usage

From source file:org.maodian.flyingcat.xmpp.codec.SASLCodec.java

@Override
public Object decode(XMLStreamReader xmlsr) {
    String mechanism = xmlsr.getAttributeValue("", "mechanism");
    if (StringUtils.equals("PLAIN", mechanism)) {
        String base64Data = null;
        try {//from  w w w .  j a v a  2  s  .  c  om
            base64Data = xmlsr.getElementText();
        } catch (XMLStreamException e) {
            throw new RuntimeException(e);
        }

        if (!Base64.isBase64(base64Data)) {
            throw new XmppException(SASLError.INCORRECT_ENCODING);
        }

        byte[] value = Base64.decodeBase64(base64Data);
        String text = new String(value, StandardCharsets.UTF_8);

        // apply PLAIN SASL mechanism whose rfc locates at http://tools.ietf.org/html/rfc4616
        int[] nullPosition = { -1, -1 };
        int nullIndex = 0;
        for (int i = 0; i < text.length(); ++i) {
            if (text.codePointAt(i) == 0) {
                // a malicious base64 value may contain more than two null character
                if (nullIndex > 1) {
                    throw new XmppException(SASLError.MALFORMED_REQUEST);
                }
                nullPosition[nullIndex++] = i;
            }
        }

        if (nullPosition[0] == -1 || nullPosition[1] == -1) {
            throw new XmppException("The format is invalid", SASLError.MALFORMED_REQUEST);
        }
        String authzid = StringUtils.substring(text, 0, nullPosition[0]);
        String authcid = StringUtils.substring(text, nullPosition[0] + 1, nullPosition[1]);
        String password = StringUtils.substring(text, nullPosition[1] + 1);

        if (authzid.getBytes(StandardCharsets.UTF_8).length > 255
                || authcid.getBytes(StandardCharsets.UTF_8).length > 255
                || password.getBytes(StandardCharsets.UTF_8).length > 255) {
            throw new XmppException(
                    "authorization id, authentication id and password should be equal or less than 255 bytes",
                    SASLError.MALFORMED_REQUEST);
        }
        return new Auth(authzid, authcid, password);
    } else {
        throw new XmppException(SASLError.INVALID_MECHANISM).set("mechanism", mechanism);
    }
}

From source file:com.muk.services.processor.BasicAuthPrincipalProcessor.java

@Override
public void process(Exchange exchange) throws Exception {
    @SuppressWarnings("unchecked")
    final List<Header> httpHeaders = exchange.getIn().getHeader("org.restlet.http.headers", List.class);

    String userpass = "bad:creds";
    for (final Header header : httpHeaders) {
        if (header.getName().toLowerCase().equals(HttpHeaders.AUTHORIZATION.toLowerCase())) {
            userpass = new String(Base64.decodeBase64(
                    (StringUtils.substringAfter(header.getValue(), " ").getBytes(StandardCharsets.UTF_8))),
                    StandardCharsets.UTF_8);
            break;
        }/*  ww  w  . j a v  a  2s  .  c om*/
    }

    final String[] tokens = userpass.split(":");

    // create an Authentication object
    // build a new bearer token type
    final UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(tokens[0],
            tokens[1]);

    // wrap it in a Subject
    final Subject subject = new Subject();
    subject.getPrincipals().add(authToken);

    // place the Subject in the In message
    exchange.getIn().setHeader(Exchange.AUTHENTICATION, subject);
}

From source file:com.quantiply.avro.AvroToJsonTest.java

@Test
public void testJsonToObject() throws Exception {
    AvroToJson avroToJson = new AvroToJson();
    User expectedUser = User.newBuilder().setAge(5).setName("Bumpkin").build();
    String jsonStr = "{\"name\":\"Bumpkin\",\"age\":5}";
    User user = avroToJson.jsonToObject(jsonStr.getBytes(StandardCharsets.UTF_8), User.class);
    assertEquals(expectedUser, user);/*from  ww  w .  j a v  a 2 s  .  co m*/
}

From source file:at.ac.tuwien.dsg.depic.dataassetfunctionmanagement.taskservice.Output.java

private void outputWithFormat(String formOfData, String dafID) {

    if (formOfData.equals(DataAssetForm.CSV.getDataAssetForm())) {

        MySqlDataAssetStore das = new MySqlDataAssetStore();

        ResultSet rs = das.getDataAssetByID(dafID);

        try {//from   w  w w .j a v a  2  s  . c  om
            while (rs.next()) {

                String dataPartitionID = rs.getString("dataPartitionID");
                InputStream inputStream = rs.getBinaryStream("data");

                StringWriter writer = new StringWriter();
                String encoding = StandardCharsets.UTF_8.name();
                //       org.apache.commons.io.IOUtils.copy(inputStream, writer, encoding);
                String daXML = writer.toString();

                DataAsset da = JAXBUtils.unmarshal(daXML, DataAsset.class);

                daXML = convertToCSV(da);
                System.out.println("CONVERT CSV: " + daXML);
                das.updateDataAsset(dafID, dataPartitionID, daXML);

            }

            rs.close();
        } catch (Exception ex) {
            Logger.getLogger(Sampling.class.getName()).log(Level.SEVERE, ex.toString());
        }

    } else if (formOfData.equals(DataAssetForm.XML.getDataAssetForm())) {
        // data in xml by default
    } else if (formOfData.equals(DataAssetForm.FIGURE.getDataAssetForm())) {
        // not implemented yet
    }

}

From source file:org.unitedinternet.cosmo.dav.impl.DavCard.java

public void writeHead(final HttpServletResponse response) throws IOException {
    Item content = (Item) getItem();/*  w  w w  . j ava  2  s .c  o m*/
    final byte[] calendar = content.getCalendar().getBytes(StandardCharsets.UTF_8);

    response.setContentType(content.getMimetype());
    response.setContentLength(calendar.length);
    if (getModificationTime() >= 0) {
        response.addDateHeader(LAST_MODIFIED, getModificationTime());
    }
    if (getETag() != null) {
        response.setHeader(ETAG, getETag());
    }
}

From source file:com.grantingersoll.opengrok.analysis.plain.TestPlainSymbolTokenizer.java

@Test
public void test() throws Exception {
    String input;//www  .  j a  v a 2 s. co  m
    try (InputStream stream = TestPlainSymbolTokenizer.class.getResourceAsStream("sample");
            Reader in = new InputStreamReader(stream, StandardCharsets.UTF_8)) {
        input = IOUtils.toString(in);
    }
    String[] output = new String[] { "Sample", "plain", "text", //// Sample plain text
            //// -----------------
            ////
            "Some", "words", "in", "here", "Two", "single", "letters", //// Some words in here.  Two single letters: a, b.
            ////
            "More", "than", "tokens", "fewer", "than", //// More than 3 tokens, fewer than 10,000.
                                                       ////
                                                       ////
    };
    assertAnalyzesTo(analyzer, input, output);
}

From source file:de.dentrassi.pm.npm.aspect.NpmExtractor.java

private void perform(final Path file, final Map<String, String> metadata) throws IOException {
    try (final GZIPInputStream gis = new GZIPInputStream(new FileInputStream(file.toFile()));
            final TarArchiveInputStream tis = new TarArchiveInputStream(gis)) {
        TarArchiveEntry entry;//from w w  w  . j  av  a  2 s  .com
        while ((entry = tis.getNextTarEntry()) != null) {
            if (entry.getName().equals("package/package.json")) {
                final byte[] data = new byte[(int) entry.getSize()];
                ByteStreams.read(tis, data, 0, data.length);

                final String str = StandardCharsets.UTF_8.decode(ByteBuffer.wrap(data)).toString();

                try {
                    // test parse
                    new JsonParser().parse(str);
                    // store
                    metadata.put("package.json", str);
                } catch (final JsonParseException e) {
                    // ignore
                }

                break; // stop parsing the archive
            }
        }

    }
}

From source file:com.haulmont.cuba.core.sys.encryption.Sha1EncryptionModule.java

@Override
public HashDescriptor getHash(String content) {
    String salt;//from  w w  w  .  j a v  a2  s.  c  om
    String result;
    try {
        salt = generateSalt();
        result = apply(content, salt.getBytes(StandardCharsets.UTF_8));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return new HashDescriptor(result, salt);
}

From source file:io.github.swagger2markup.internal.component.VersionInfoComponentTest.java

@Test
public void testVersionInfoComponent() throws URISyntaxException {

    Info info = new Info().version("1.0");

    Swagger2MarkupConverter.Context context = createContext();
    MarkupDocBuilder markupDocBuilder = context.createMarkupDocBuilder();

    markupDocBuilder = new VersionInfoComponent(context).apply(markupDocBuilder,
            VersionInfoComponent.parameters(info, OverviewDocument.SECTION_TITLE_LEVEL));
    markupDocBuilder.writeToFileWithoutExtension(outputDirectory, StandardCharsets.UTF_8);

    Path expectedFile = getExpectedFile(COMPONENT_NAME);
    DiffUtils.assertThatFileIsEqual(expectedFile, outputDirectory, getReportName(COMPONENT_NAME));

}

From source file:com.apm4all.tracy.TracyCloseableHttpClientPublisher.java

private String extractPostResponse(CloseableHttpResponse response) throws ParseException, IOException {
    StringBuilder sb = new StringBuilder(1024);
    HttpEntity entity = response.getEntity();
    sb.append(response.getStatusLine());
    sb.append(" ");
    sb.append(EntityUtils.toString(entity, StandardCharsets.UTF_8));
    EntityUtils.consume(entity);//from  ww  w  . j ava 2 s .  c om
    return sb.toString();
}