Example usage for java.nio.charset Charset name

List of usage examples for java.nio.charset Charset name

Introduction

In this page you can find the example usage for java.nio.charset Charset name.

Prototype

String name

To view the source code for java.nio.charset Charset name.

Click Source Link

Usage

From source file:de.hanbei.httpserver.response.ResponseBuilder.java

/**
 * Set the content as a String. The content length is induced from the string length
 *
 * @param content The content as as a string.
 * @param charset The character set the content should be encoded in.
 * @return A ResponseBuilder to add additional information.
 *//*from w  w  w.  j  a v a2s  .  c om*/
public ResponseBuilder content(String content, Charset charset) {
    content(content.getBytes(charset));
    response.getContent().setCharset(charset.name());
    response.getContent().setString(true);
    return this;
}

From source file:com.anrisoftware.sscontrol.scripts.locale.ubuntu_12_04.Ubuntu_12_04_InstallLocale.java

private void writeLocales(File file, Charset charset, List<String> lines) throws ScriptException {
    try {//from   w  w w . j  av  a  2  s.  c  o  m
        FileUtils.writeLines(file, charset.name(), lines);
    } catch (IOException e) {
        throw log.errorAttachLocale(this, e, file);
    }
}

From source file:com.github.zdsiyan.maven.plugin.smartconfig.internal.PropertyConfigurator.java

@Override
public ByteArrayOutputStream execute(InputStream in, Charset charset, List<PointHandle> pointhandles)
        throws IOException {
    try {//from w ww .j  a  v  a2s  .  c  om
        PropertiesConfiguration configuration = new PropertiesConfiguration();
        configuration.load(in, charset.name());

        pointhandles.forEach(point -> {
            switch (point.getMode()) {
            case insert:
                configuration.addProperty(point.getExpression(), point.getValue());
                break;
            case delete:
                configuration.setProperty(point.getExpression(), "");
                break;
            case replace:
            default:
                configuration.setProperty(point.getExpression(), point.getValue());
                break;
            }
        });

        // output
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        configuration.save(out, charset.name());
        return out;
    } catch (ConfigurationException ex) {
        // FIXME
        throw new RuntimeException(ex);
    }
}

From source file:com.twinsoft.convertigo.eclipse.popup.actions.SequenceImportFromXmlAction.java

public void run() {
    Display display = Display.getDefault();
    Cursor waitCursor = new Cursor(display, SWT.CURSOR_WAIT);

    Shell shell = getParentShell();/*from  w  ww.  j  a v a2s . c  o m*/
    shell.setCursor(waitCursor);

    try {
        ProjectExplorerView explorerView = getProjectExplorerView();
        if (explorerView != null) {
            DatabaseObjectTreeObject databaseObjectTreeObject = (DatabaseObjectTreeObject) explorerView
                    .getFirstSelectedTreeObject();
            DatabaseObject databaseObject = databaseObjectTreeObject.getObject();
            SequenceTreeObject sequenceTreeObject = (SequenceTreeObject) ((databaseObject instanceof Sequence)
                    ? databaseObjectTreeObject
                    : databaseObjectTreeObject.getParentDatabaseObjectTreeObject());
            Sequence sequence = (databaseObject instanceof Sequence) ? (Sequence) databaseObject
                    : ((StepWithExpressions) databaseObject).getSequence();

            // Open a file dialog to search a XML file
            FileDialog fileDialog = new FileDialog(shell, SWT.PRIMARY_MODAL | SWT.SAVE);
            fileDialog.setText("Import XML file");
            fileDialog.setFilterExtensions(new String[] { "*.xml" });
            fileDialog.setFilterNames(new String[] { "XML" });
            fileDialog.setFilterPath(Engine.PROJECTS_PATH);

            String filePath = fileDialog.open();

            if (filePath != null) {
                // Get XML content from the file
                File xmlFile = new File(filePath);
                Charset charset = XMLUtils.getEncoding(xmlFile);
                String xmlContent = FileUtils.readFileToString(xmlFile, charset.name());

                // Open and add XML content to the dialog area
                XmlStructureDialog dlg = new XmlStructureDialog(shell, sequence, xmlContent);

                if (dlg.open() == Window.OK) {
                    if (dlg.result instanceof Throwable) {
                        throw (Throwable) dlg.result;
                    } else {
                        Step step = (Step) dlg.result;
                        if (step != null) {
                            if (databaseObject instanceof Sequence) {
                                sequence.addStep(step);
                            } else {
                                StepWithExpressions swe = (StepWithExpressions) databaseObject;
                                swe.addStep(step);
                            }

                            sequence.hasChanged = true;

                            // Reload sequence in tree without updating its schema for faster reload
                            ConvertigoPlugin.logDebug("Reload sequence: start");
                            explorerView.reloadTreeObject(sequenceTreeObject);
                            ConvertigoPlugin.logDebug("Reload sequence: end");

                            // Select target dbo in tree
                            explorerView.objectSelected(new CompositeEvent(databaseObject));
                        }
                    }
                }
            }
        }
    } catch (Throwable e) {
        ConvertigoPlugin.logException(e, "Unable to import step from xml!");
    } finally {
        shell.setCursor(null);
        waitCursor.dispose();
    }
}

From source file:org.apache.nutch.indexer.TestIndexerMapReduce.java

/**
 * Test indexing of base64-encoded binary content.
 *///from  ww w  .j  a  v a 2s .c om
@Test
public void testBinaryContentBase64() {
    configuration = NutchConfiguration.create();
    configuration.setBoolean(IndexerMapReduce.INDEXER_BINARY_AS_BASE64, true);

    Charset[] testCharsets = { StandardCharsets.UTF_8, Charset.forName("iso-8859-1"),
            Charset.forName("iso-8859-2") };
    for (Charset charset : testCharsets) {
        LOG.info("Testing indexing binary content as base64 for charset {}", charset.name());

        String htmlDoc = testHtmlDoc;
        if (charset != StandardCharsets.UTF_8) {
            htmlDoc = htmlDoc.replaceAll("utf-8", charset.name());
            if (charset.name().equalsIgnoreCase("iso-8859-1")) {
                // Western-European character set: remove Czech content
                htmlDoc = htmlDoc.replaceAll("\\s*<[^>]+\\slang=\"cs\".+?\\n", "");
            } else if (charset.name().equalsIgnoreCase("iso-8859-2")) {
                // Eastern-European character set: remove French content
                htmlDoc = htmlDoc.replaceAll("\\s*<[^>]+\\slang=\"fr\".+?\\n", "");
            }
        }

        Content content = new Content(testUrl, testUrl, htmlDoc.getBytes(charset), htmlContentType, htmlMeta,
                configuration);

        NutchDocument doc = runIndexer(crawlDatumDbFetched, crawlDatumFetchSuccess, parseText, parseData,
                content);
        assertNotNull("No NutchDocument indexed", doc);

        String binaryContentBase64 = (String) doc.getField("binaryContent").getValues().get(0);
        LOG.info("binary content (base64): {}", binaryContentBase64);
        String binaryContent = new String(Base64.decodeBase64(binaryContentBase64), charset);
        LOG.info("binary content (decoded): {}", binaryContent);
        assertEquals("Binary content (" + charset + ") not correctly saved as base64", htmlDoc, binaryContent);
    }
}

From source file:com.wudaosoft.net.httpclient.XmlResponseHandler.java

@Override
public XmlObject handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
    int status = response.getStatusLine().getStatusCode();

    if (status < 200 || status >= 300) {
        throw new ClientProtocolException("Unexpected response status: " + status);
    }/* ww w  .j  av a  2  s.  c o m*/

    HttpEntity entity = response.getEntity();

    if (entity == null) {
        throw new ClientProtocolException("Response contains no content");
    }

    DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
    dbfac.setIgnoringElementContentWhitespace(true);
    dbfac.setCoalescing(true);
    dbfac.setIgnoringComments(true);
    try {
        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
        ContentType contentType = ContentType.getOrDefault(entity);
        //            if (!contentType.equals(ContentType.APPLICATION_XML)) {
        //                throw new ClientProtocolException("Unexpected content type:" +
        //                    contentType);
        //            }
        Charset charset = contentType.getCharset();
        if (charset == null) {
            charset = Consts.UTF_8;
        }
        return XmlObject.fromDocument(docBuilder.parse(entity.getContent(), charset.name()));
    } catch (ParserConfigurationException ex) {
        throw new IllegalStateException(ex);
    } catch (SAXException ex) {
        throw new ClientProtocolException("Malformed XML document", ex);
    }
}

From source file:org.apache.tika.parser.envi.EnviHeaderParser.java

public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context)
        throws IOException, SAXException, TikaException {

    // Only outputting the MIME type as metadata
    metadata.set(Metadata.CONTENT_TYPE, ENVI_MIME_TYPE);

    // The following code was taken from the TXTParser
    // Automatically detect the character encoding

    TikaConfig tikaConfig = context.get(TikaConfig.class);
    if (tikaConfig == null) {
        tikaConfig = TikaConfig.getDefaultConfig();
    }/*from  w  w w .  j a va 2s  . c o m*/
    try (AutoDetectReader reader = new AutoDetectReader(new CloseShieldInputStream(stream), metadata,
            getEncodingDetector(context))) {
        Charset charset = reader.getCharset();
        MediaType type = new MediaType(MediaType.TEXT_PLAIN, charset);
        // deprecated, see TIKA-431
        metadata.set(Metadata.CONTENT_ENCODING, charset.name());

        XHTMLContentHandler xhtml = new XHTMLContentHandler(handler, metadata);

        xhtml.startDocument();

        // text contents of the xhtml
        String line;
        while ((line = reader.readLine()) != null) {
            xhtml.startElement("p");
            xhtml.characters(line);
            xhtml.endElement("p");
        }

        xhtml.endDocument();
    }
}

From source file:org.apereo.portal.portlet.container.PortletResourceResponseContextImpl.java

/**
 * Handles resource response specific headers. Returns true if the header was consumed by this method and requires no further processing
 * //from ww w  .j a  va  2s. c o  m
 * @return
 */
protected boolean handleResourceHeader(String key, String value) {
    if (ResourceResponse.HTTP_STATUS_CODE.equals(key)) {
        this.portletResourceOutputHandler.setStatus(Integer.parseInt(value));
        return true;
    }
    if ("Content-Type".equals(key)) {
        final ContentType contentType = ContentType.parse(value);
        final Charset charset = contentType.getCharset();
        if (charset != null) {
            this.portletResourceOutputHandler.setCharacterEncoding(charset.name());
        }
        this.portletResourceOutputHandler.setContentType(contentType.getMimeType());
        return true;
    }
    if ("Content-Length".equals(key)) {
        this.portletResourceOutputHandler.setContentLength(Integer.parseInt(value));
        return true;
    }
    if ("Content-Language".equals(key)) {
        final HeaderElement[] parts = BasicHeaderValueParser.parseElements(value, null);
        if (parts.length > 0) {
            final String localeStr = parts[0].getValue();
            final Locale locale = LocaleUtils.toLocale(localeStr);
            this.portletResourceOutputHandler.setLocale(locale);
            return true;
        }
    }

    return false;
}

From source file:org.springframework.http.server.reactive.ServletServerHttpResponse.java

@Override
protected void writeHeaders() {
    for (Map.Entry<String, List<String>> entry : getHeaders().entrySet()) {
        String headerName = entry.getKey();
        for (String headerValue : entry.getValue()) {
            this.response.addHeader(headerName, headerValue);
        }//from   w w  w . j a v a 2  s  .  com
    }
    MediaType contentType = getHeaders().getContentType();
    if (this.response.getContentType() == null && contentType != null) {
        this.response.setContentType(contentType.toString());
    }
    Charset charset = (contentType != null ? contentType.getCharSet() : null);
    if (this.response.getCharacterEncoding() == null && charset != null) {
        this.response.setCharacterEncoding(charset.name());
    }
}

From source file:org.sventon.model.ZipFileWrapper.java

/**
 * Constructor.//ww  w  . j  a  va 2  s.c o  m
 *
 * @param zipFile Destination ZIP file.
 * @param charset Charset to use for file names and comments.
 */
public ZipFileWrapper(final File zipFile, final Charset charset) {
    Validate.notNull(charset, "Charset was null");
    Validate.notNull(zipFile, "ZipFile was null");
    this.zipFile = zipFile;

    final ArchiveDriver driver = new Zip32Driver(charset.name());
    de.schlichtherle.io.File
            .setDefaultArchiveDetector(new DefaultArchiveDetector(ArchiveDetector.DEFAULT, "zip", driver));
}