Search in sources :

Example 21 with UnsupportedCharsetException

use of java.nio.charset.UnsupportedCharsetException in project undertow by undertow-io.

the class HttpServletRequestImpl method setCharacterEncoding.

@Override
public void setCharacterEncoding(final String env) throws UnsupportedEncodingException {
    if (readStarted) {
        return;
    }
    try {
        characterEncoding = Charset.forName(env);
        final ManagedServlet originalServlet = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY).getOriginalServletPathMatch().getServletChain().getManagedServlet();
        final FormDataParser parser = originalServlet.getFormParserFactory().createParser(exchange);
        if (parser != null) {
            parser.setCharacterEncoding(env);
        }
    } catch (UnsupportedCharsetException e) {
        throw new UnsupportedEncodingException();
    }
}
Also used : ManagedServlet(io.undertow.servlet.core.ManagedServlet) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) FormDataParser(io.undertow.server.handlers.form.FormDataParser) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 22 with UnsupportedCharsetException

use of java.nio.charset.UnsupportedCharsetException in project android by JetBrains.

the class EncodingValidationStrategy method validate.

@Override
void validate(@NotNull Module module, @NotNull AndroidModuleModel androidModel) {
    GradleVersion modelVersion = (androidModel.getModelVersion());
    if (modelVersion != null) {
        boolean isOneDotTwoOrNewer = modelVersion.compareIgnoringQualifiers(myOneDotTwoPluginVersion) >= 0;
        // Verify that the encoding in the model is the same as the encoding in the IDE's project settings.
        Charset modelEncoding = null;
        if (isOneDotTwoOrNewer) {
            try {
                AndroidProject androidProject = androidModel.getAndroidProject();
                modelEncoding = Charset.forName(androidProject.getJavaCompileOptions().getEncoding());
            } catch (UnsupportedCharsetException ignore) {
            // It's not going to happen.
            }
        }
        if (myMismatchingEncoding == null && modelEncoding != null && myProjectEncoding.compareTo(modelEncoding) != 0) {
            myMismatchingEncoding = modelEncoding.displayName();
        }
    }
}
Also used : UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) Charset(java.nio.charset.Charset) AndroidProject(com.android.builder.model.AndroidProject) GradleVersion(com.android.ide.common.repository.GradleVersion)

Example 23 with UnsupportedCharsetException

use of java.nio.charset.UnsupportedCharsetException in project android by JetBrains.

the class GradleImport method getEncodingFromWorkspaceSetting.

@Nullable
private Charset getEncodingFromWorkspaceSetting() {
    if (myWorkspaceLocation != null && !myDefaultEncodingInitialized) {
        myDefaultEncodingInitialized = true;
        File settings = getEncodingSettingsFile();
        if (settings.exists()) {
            try {
                Properties properties = PropertiesFiles.getProperties(settings);
                if (properties != null) {
                    String encodingName = properties.getProperty("encoding");
                    if (encodingName != null) {
                        try {
                            myDefaultEncoding = Charset.forName(encodingName);
                        } catch (UnsupportedCharsetException uce) {
                            reportWarning((ImportModule) null, settings, "Unknown charset " + encodingName);
                        }
                    }
                }
            } catch (IOException e) {
            // ignore properties
            }
        }
    }
    return myDefaultEncoding;
}
Also used : UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) IOException(java.io.IOException) File(java.io.File) Nullable(com.android.annotations.Nullable)

Example 24 with UnsupportedCharsetException

use of java.nio.charset.UnsupportedCharsetException in project jdk8u_jdk by JetBrains.

the class URLEncoder method encode.

/**
     * Translates a string into {@code application/x-www-form-urlencoded}
     * format using a specific encoding scheme. This method uses the
     * supplied encoding scheme to obtain the bytes for unsafe
     * characters.
     * <p>
     * <em><strong>Note:</strong> The <a href=
     * "http://www.w3.org/TR/html40/appendix/notes.html#non-ascii-chars">
     * World Wide Web Consortium Recommendation</a> states that
     * UTF-8 should be used. Not doing so may introduce
     * incompatibilities.</em>
     *
     * @param   s   {@code String} to be translated.
     * @param   enc   The name of a supported
     *    <a href="../lang/package-summary.html#charenc">character
     *    encoding</a>.
     * @return  the translated {@code String}.
     * @exception  UnsupportedEncodingException
     *             If the named encoding is not supported
     * @see URLDecoder#decode(java.lang.String, java.lang.String)
     * @since 1.4
     */
public static String encode(String s, String enc) throws UnsupportedEncodingException {
    boolean needToChange = false;
    StringBuffer out = new StringBuffer(s.length());
    Charset charset;
    CharArrayWriter charArrayWriter = new CharArrayWriter();
    if (enc == null)
        throw new NullPointerException("charsetName");
    try {
        charset = Charset.forName(enc);
    } catch (IllegalCharsetNameException e) {
        throw new UnsupportedEncodingException(enc);
    } catch (UnsupportedCharsetException e) {
        throw new UnsupportedEncodingException(enc);
    }
    for (int i = 0; i < s.length(); ) {
        int c = (int) s.charAt(i);
        //System.out.println("Examining character: " + c);
        if (dontNeedEncoding.get(c)) {
            if (c == ' ') {
                c = '+';
                needToChange = true;
            }
            //System.out.println("Storing: " + c);
            out.append((char) c);
            i++;
        } else {
            // convert to external encoding before hex conversion
            do {
                charArrayWriter.write(c);
                /*
                     * If this character represents the start of a Unicode
                     * surrogate pair, then pass in two characters. It's not
                     * clear what should be done if a bytes reserved in the
                     * surrogate pairs range occurs outside of a legal
                     * surrogate pair. For now, just treat it as if it were
                     * any other character.
                     */
                if (c >= 0xD800 && c <= 0xDBFF) {
                    /*
                          System.out.println(Integer.toHexString(c)
                          + " is high surrogate");
                        */
                    if ((i + 1) < s.length()) {
                        int d = (int) s.charAt(i + 1);
                        /*
                              System.out.println("\tExamining "
                              + Integer.toHexString(d));
                            */
                        if (d >= 0xDC00 && d <= 0xDFFF) {
                            /*
                                  System.out.println("\t"
                                  + Integer.toHexString(d)
                                  + " is low surrogate");
                                */
                            charArrayWriter.write(d);
                            i++;
                        }
                    }
                }
                i++;
            } while (i < s.length() && !dontNeedEncoding.get((c = (int) s.charAt(i))));
            charArrayWriter.flush();
            String str = new String(charArrayWriter.toCharArray());
            byte[] ba = str.getBytes(charset);
            for (int j = 0; j < ba.length; j++) {
                out.append('%');
                char ch = Character.forDigit((ba[j] >> 4) & 0xF, 16);
                // the hex value if ch is a letter.
                if (Character.isLetter(ch)) {
                    ch -= caseDiff;
                }
                out.append(ch);
                ch = Character.forDigit(ba[j] & 0xF, 16);
                if (Character.isLetter(ch)) {
                    ch -= caseDiff;
                }
                out.append(ch);
            }
            charArrayWriter.reset();
            needToChange = true;
        }
    }
    return (needToChange ? out.toString() : s);
}
Also used : IllegalCharsetNameException(java.nio.charset.IllegalCharsetNameException) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) Charset(java.nio.charset.Charset) UnsupportedEncodingException(java.io.UnsupportedEncodingException) CharArrayWriter(java.io.CharArrayWriter)

Example 25 with UnsupportedCharsetException

use of java.nio.charset.UnsupportedCharsetException in project jabref by JabRef.

the class SaveDatabaseAction method saveDatabase.

private boolean saveDatabase(File file, boolean selectedOnly, Charset encoding) throws SaveException {
    SaveSession session;
    // block user input
    frame.block();
    try {
        SavePreferences prefs = SavePreferences.loadForSaveFromPreferences(Globals.prefs).withEncoding(encoding);
        BibtexDatabaseWriter<SaveSession> databaseWriter = new BibtexDatabaseWriter<>(FileSaveSession::new);
        if (selectedOnly) {
            session = databaseWriter.savePartOfDatabase(panel.getBibDatabaseContext(), panel.getSelectedEntries(), prefs);
        } else {
            session = databaseWriter.saveDatabase(panel.getBibDatabaseContext(), prefs);
        }
        panel.registerUndoableChanges(session);
    } catch (UnsupportedCharsetException ex) {
        JOptionPane.showMessageDialog(frame, Localization.lang("Could not save file.") + Localization.lang("Character encoding '%0' is not supported.", encoding.displayName()), Localization.lang("Save library"), JOptionPane.ERROR_MESSAGE);
        // FIXME: rethrow anti-pattern
        throw new SaveException("rt");
    } catch (SaveException ex) {
        if (ex == SaveException.FILE_LOCKED) {
            throw ex;
        }
        if (ex.specificEntry()) {
            BibEntry entry = ex.getEntry();
            // Error occured during processing of an entry. Highlight it!
            panel.highlightEntry(entry);
        } else {
            LOGGER.error("A problem occured when trying to save the file", ex);
        }
        JOptionPane.showMessageDialog(frame, Localization.lang("Could not save file.") + ".\n" + ex.getMessage(), Localization.lang("Save library"), JOptionPane.ERROR_MESSAGE);
        // FIXME: rethrow anti-pattern
        throw new SaveException("rt");
    } finally {
        // re-enable user input
        frame.unblock();
    }
    // handle encoding problems
    boolean success = true;
    if (!session.getWriter().couldEncodeAll()) {
        FormBuilder builder = FormBuilder.create().layout(new FormLayout("left:pref, 4dlu, fill:pref", "pref, 4dlu, pref"));
        JTextArea ta = new JTextArea(session.getWriter().getProblemCharacters());
        ta.setEditable(false);
        builder.add(Localization.lang("The chosen encoding '%0' could not encode the following characters:", session.getEncoding().displayName())).xy(1, 1);
        builder.add(ta).xy(3, 1);
        builder.add(Localization.lang("What do you want to do?")).xy(1, 3);
        String tryDiff = Localization.lang("Try different encoding");
        int answer = JOptionPane.showOptionDialog(frame, builder.getPanel(), Localization.lang("Save library"), JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null, new String[] { Localization.lang("Save"), tryDiff, Localization.lang("Cancel") }, tryDiff);
        if (answer == JOptionPane.NO_OPTION) {
            // The user wants to use another encoding.
            Object choice = JOptionPane.showInputDialog(frame, Localization.lang("Select encoding"), Localization.lang("Save library"), JOptionPane.QUESTION_MESSAGE, null, Encodings.ENCODINGS_DISPLAYNAMES, encoding);
            if (choice == null) {
                success = false;
            } else {
                Charset newEncoding = Charset.forName((String) choice);
                return saveDatabase(file, selectedOnly, newEncoding);
            }
        } else if (answer == JOptionPane.CANCEL_OPTION) {
            success = false;
        }
    }
    // backup file?
    try {
        if (success) {
            session.commit(file.toPath());
            // Make sure to remember which encoding we used.
            panel.getBibDatabaseContext().getMetaData().setEncoding(encoding, ChangePropagation.DO_NOT_POST_EVENT);
        } else {
            session.cancel();
        }
    } catch (SaveException e) {
        int ans = JOptionPane.showConfirmDialog(null, Localization.lang("Save failed during backup creation") + ". " + Localization.lang("Save without backup?"), Localization.lang("Unable to create backup"), JOptionPane.YES_NO_OPTION);
        if (ans == JOptionPane.YES_OPTION) {
            session.setUseBackup(false);
            session.commit(file.toPath());
            panel.getBibDatabaseContext().getMetaData().setEncoding(encoding, ChangePropagation.DO_NOT_POST_EVENT);
        } else {
            success = false;
        }
    }
    return success;
}
Also used : FormLayout(com.jgoodies.forms.layout.FormLayout) BibEntry(org.jabref.model.entry.BibEntry) FormBuilder(com.jgoodies.forms.builder.FormBuilder) SaveException(org.jabref.logic.exporter.SaveException) JTextArea(javax.swing.JTextArea) BibtexDatabaseWriter(org.jabref.logic.exporter.BibtexDatabaseWriter) FileSaveSession(org.jabref.logic.exporter.FileSaveSession) Charset(java.nio.charset.Charset) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) SavePreferences(org.jabref.logic.exporter.SavePreferences) SaveSession(org.jabref.logic.exporter.SaveSession) FileSaveSession(org.jabref.logic.exporter.FileSaveSession)

Aggregations

UnsupportedCharsetException (java.nio.charset.UnsupportedCharsetException)46 Charset (java.nio.charset.Charset)18 IllegalCharsetNameException (java.nio.charset.IllegalCharsetNameException)13 IOException (java.io.IOException)10 File (java.io.File)9 UnsupportedEncodingException (java.io.UnsupportedEncodingException)5 FileOutputStream (java.io.FileOutputStream)4 PrintStream (java.io.PrintStream)4 HashMap (java.util.HashMap)4 ByteArrayInputStream (java.io.ByteArrayInputStream)3 FileInputStream (java.io.FileInputStream)3 InputStream (java.io.InputStream)3 Test (org.junit.Test)3 FormBuilder (com.jgoodies.forms.builder.FormBuilder)2 FormLayout (com.jgoodies.forms.layout.FormLayout)2 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)2 InputStreamReader (java.io.InputStreamReader)2 StringReader (java.io.StringReader)2 ReadableByteChannel (java.nio.channels.ReadableByteChannel)2 WritableByteChannel (java.nio.channels.WritableByteChannel)2