Search in sources :

Example 31 with IllegalCharsetNameException

use of java.nio.charset.IllegalCharsetNameException in project Payara by payara.

the class JwtKeyStoreUtils method readKeyFromURL.

private static CacheableString readKeyFromURL(URL keyURL, Duration defaultCacheTTL) throws IOException {
    URLConnection urlConnection = keyURL.openConnection();
    Charset charset = Charset.defaultCharset();
    ContentType contentType = ContentType.newContentType(urlConnection.getContentType());
    if (contentType != null) {
        String charEncoding = contentType.getCharacterEncoding();
        if (charEncoding != null) {
            try {
                if (!Charset.isSupported(charEncoding)) {
                    LOGGER.warning("Charset " + charEncoding + " for remote key not supported, using default charset instead");
                } else {
                    charset = Charset.forName(contentType.getCharacterEncoding());
                }
            } catch (IllegalCharsetNameException ex) {
                LOGGER.severe("Charset " + ex.getCharsetName() + " for remote key not supported, Cause: " + ex.getMessage());
            }
        }
    }
    // There's no guarantee that the response will contain at most one Cache-Control header and at most one max-age
    // directive. Here, we apply the smallest of all max-age directives.
    Duration cacheTTL = urlConnection.getHeaderFields().entrySet().stream().filter(e -> e.getKey() != null && e.getKey().trim().equalsIgnoreCase("Cache-Control")).flatMap(headers -> headers.getValue().stream()).flatMap(headerValue -> Stream.of(headerValue.split(","))).filter(directive -> directive.trim().startsWith("max-age")).map(maxAgeDirective -> {
        String[] keyValue = maxAgeDirective.split("=", 2);
        String maxAge = keyValue[keyValue.length - 1];
        try {
            return Duration.ofSeconds(Long.parseLong(maxAge));
        } catch (NumberFormatException e) {
            return null;
        }
    }).filter(Objects::nonNull).min(Duration::compareTo).orElse(defaultCacheTTL);
    try (InputStream inputStream = urlConnection.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, charset))) {
        String keyContents = reader.lines().collect(Collectors.joining(System.lineSeparator()));
        return CacheableString.from(keyContents, cacheTTL);
    }
}
Also used : URL(java.net.URL) Thread.currentThread(java.lang.Thread.currentThread) JsonValue(javax.json.JsonValue) ByteArrayInputStream(java.io.ByteArrayInputStream) Charset(java.nio.charset.Charset) URLConnection(java.net.URLConnection) Duration(java.time.Duration) Json(javax.json.Json) IllegalCharsetNameException(java.nio.charset.IllegalCharsetNameException) JsonObject(javax.json.JsonObject) JsonReader(javax.json.JsonReader) MalformedURLException(java.net.MalformedURLException) JsonArray(javax.json.JsonArray) IOException(java.io.IOException) Config(org.eclipse.microprofile.config.Config) Logger(java.util.logging.Logger) InputStreamReader(java.io.InputStreamReader) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) Base64(java.util.Base64) ContentType(org.glassfish.grizzly.http.util.ContentType) Stream(java.util.stream.Stream) StringReader(java.io.StringReader) Optional(java.util.Optional) BufferedReader(java.io.BufferedReader) InputStream(java.io.InputStream) IllegalCharsetNameException(java.nio.charset.IllegalCharsetNameException) ContentType(org.glassfish.grizzly.http.util.ContentType) InputStreamReader(java.io.InputStreamReader) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Objects(java.util.Objects) BufferedReader(java.io.BufferedReader) Charset(java.nio.charset.Charset) Duration(java.time.Duration) URLConnection(java.net.URLConnection)

Example 32 with IllegalCharsetNameException

use of java.nio.charset.IllegalCharsetNameException in project openj9 by eclipse.

the class FileSniffer method attemptCharset.

private static Charset attemptCharset(ByteBuffer headByteBuffer, Charset trialCharset) throws IOException {
    final String sectionEyeCatcher = "0SECTION";
    final String charsetEyeCatcher = "1TICHARSET";
    headByteBuffer.rewind();
    String head = trialCharset.decode(headByteBuffer).toString();
    /* If we can find the section eyecatcher, this encoding is mostly good */
    if (head.indexOf(sectionEyeCatcher) >= 0) {
        int idx = head.indexOf(charsetEyeCatcher);
        /* The charset eyecatcher is much newer, so may not be present */
        if (idx >= 0) {
            idx += charsetEyeCatcher.length();
            String javacoreCharset = head.substring(idx).trim();
            javacoreCharset = javacoreCharset.split("\\s+")[0];
            try {
                Charset trueCharset = Charset.forName(javacoreCharset);
                /*
					 * Check if trueCharset would have encoded the sectionEyeCatcher the
					 * same way.
					 */
                ByteBuffer sanityTrial = trialCharset.encode(sectionEyeCatcher);
                ByteBuffer sanityTrue = trueCharset.encode(sectionEyeCatcher);
                if (sanityTrial.equals(sanityTrue)) {
                    // Encoding matches, the trueCharset from 1TICHARSET will be the best one to return.
                    return trueCharset;
                }
            /*
				* Ignore exceptions, if the trueCharset from 1TICHARSET is illegal or unknown we
				* will return the trialCharset that read 0SECTION correctly.
				*/
            } catch (IllegalCharsetNameException e) {
            } catch (UnsupportedCharsetException e) {
            }
        }
        return trialCharset;
    }
    /* Failed to find section eyecatcher after decoding in this charset. */
    return null;
}
Also used : IllegalCharsetNameException(java.nio.charset.IllegalCharsetNameException) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) Charset(java.nio.charset.Charset) ByteBuffer(java.nio.ByteBuffer)

Example 33 with IllegalCharsetNameException

use of java.nio.charset.IllegalCharsetNameException in project graal by oracle.

the class CommonMIMETypeTestDetector method findEncoding.

@Override
public Charset findEncoding(TruffleFile file) throws IOException {
    String name = file.getName();
    if (name.endsWith(".xml")) {
        String content = new String(file.readAllBytes(), "UTF-8");
        Matcher m = ENCODING_PATTERN.matcher(content);
        if (m.find()) {
            String encoding = m.group(1);
            try {
                return Charset.forName(encoding);
            } catch (IllegalCharsetNameException | UnsupportedCharsetException e) {
            // pass and return null
            }
        }
    }
    return null;
}
Also used : IllegalCharsetNameException(java.nio.charset.IllegalCharsetNameException) Matcher(java.util.regex.Matcher) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException)

Example 34 with IllegalCharsetNameException

use of java.nio.charset.IllegalCharsetNameException in project che by eclipse.

the class TextSearchVisitor method processFile.

/**
//	 * @return returns a map from IFile to IDocument for all open, dirty editors
//	 */
//	private Map evalNonFileBufferDocuments() {
//		Map result = new HashMap();
//		IWorkbench workbench = SearchPlugin.getDefault().getWorkbench();
//		IWorkbenchWindow[] windows = workbench.getWorkbenchWindows();
//		for (int i = 0; i < windows.length; i++) {
//			IWorkbenchPage[] pages = windows[i].getPages();
//			for (int x = 0; x < pages.length; x++) {
//				IEditorReference[] editorRefs = pages[x].getEditorReferences();
//				for (int z = 0; z < editorRefs.length; z++) {
//					IEditorPart ep = editorRefs[z].getEditor(false);
//					if (ep instanceof ITextEditor && ep.isDirty()) { // only dirty editors
//						evaluateTextEditor(result, ep);
//					}
//				}
//			}
//		}
//		return result;
//	}
//	private void evaluateTextEditor(Map result, IEditorPart ep) {
//		IEditorInput input= ep.getEditorInput();
//		if (input instanceof IFileEditorInput) {
//			IFile file= ((IFileEditorInput) input).getFile();
//			if (!result.containsKey(file)) { // take the first editor found
//				ITextFileBufferManager bufferManager= FileBuffers.getTextFileBufferManager();
//				ITextFileBuffer textFileBuffer= bufferManager.getTextFileBuffer(file.getFullPath(), LocationKind.IFILE);
//				if (textFileBuffer != null) {
//					// file buffer has precedence
//					result.put(file, textFileBuffer.getDocument());
//				} else {
//					// use document provider
//					IDocument document= ((ITextEditor) ep).getDocumentProvider().getDocument(input);
//					if (document != null) {
//						result.put(file, document);
//					}
//				}
//			}
//		}
//	}
public boolean processFile(IFile file, Map documentsInEditors) {
    try {
        if (!fCollector.acceptFile(file) || fMatcher == null) {
            return true;
        }
        IDocument document = getOpenDocument(file, documentsInEditors);
        if (document != null) {
            DocumentCharSequence documentCharSequence = new DocumentCharSequence(document);
            // assume all documents are non-binary
            locateMatches(file, documentCharSequence);
        } else {
            CharSequence seq = null;
            try {
                seq = fFileCharSequenceProvider.newCharSequence(file);
                if (hasBinaryContent(seq, file) && !fCollector.reportBinaryFile(file)) {
                    return true;
                }
                locateMatches(file, seq);
            } catch (FileCharSequenceProvider.FileCharSequenceException e) {
                e.throwWrappedException();
            } finally {
                if (seq != null) {
                    try {
                        fFileCharSequenceProvider.releaseCharSequence(seq);
                    } catch (IOException e) {
                        SearchPlugin.log(e);
                    }
                }
            }
        }
    } catch (UnsupportedCharsetException e) {
        String[] args = { getCharSetName(file), file.getFullPath().makeRelative().toString() };
        String message = Messages.format(SearchMessages.TextSearchVisitor_unsupportedcharset, args);
        fStatus.add(new Status(IStatus.ERROR, NewSearchUI.PLUGIN_ID, IStatus.ERROR, message, e));
    } catch (IllegalCharsetNameException e) {
        String[] args = { getCharSetName(file), file.getFullPath().makeRelative().toString() };
        String message = Messages.format(SearchMessages.TextSearchVisitor_illegalcharset, args);
        fStatus.add(new Status(IStatus.ERROR, NewSearchUI.PLUGIN_ID, IStatus.ERROR, message, e));
    } catch (IOException e) {
        String[] args = { getExceptionMessage(e), file.getFullPath().makeRelative().toString() };
        String message = Messages.format(SearchMessages.TextSearchVisitor_error, args);
        fStatus.add(new Status(IStatus.ERROR, NewSearchUI.PLUGIN_ID, IStatus.ERROR, message, e));
    } catch (CoreException e) {
        String[] args = { getExceptionMessage(e), file.getFullPath().makeRelative().toString() };
        String message = Messages.format(SearchMessages.TextSearchVisitor_error, args);
        fStatus.add(new Status(IStatus.ERROR, NewSearchUI.PLUGIN_ID, IStatus.ERROR, message, e));
    } catch (StackOverflowError e) {
        String message = SearchMessages.TextSearchVisitor_patterntoocomplex0;
        fStatus.add(new Status(IStatus.ERROR, NewSearchUI.PLUGIN_ID, IStatus.ERROR, message, e));
        return false;
    } finally {
        fNumberOfScannedFiles++;
    }
    if (fProgressMonitor.isCanceled())
        throw new OperationCanceledException(SearchMessages.TextSearchVisitor_canceled);
    return true;
}
Also used : MultiStatus(org.eclipse.core.runtime.MultiStatus) IStatus(org.eclipse.core.runtime.IStatus) Status(org.eclipse.core.runtime.Status) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) IOException(java.io.IOException) IllegalCharsetNameException(java.nio.charset.IllegalCharsetNameException) FileCharSequenceException(org.eclipse.search.internal.core.text.FileCharSequenceProvider.FileCharSequenceException) CoreException(org.eclipse.core.runtime.CoreException) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) IDocument(org.eclipse.jface.text.IDocument)

Example 35 with IllegalCharsetNameException

use of java.nio.charset.IllegalCharsetNameException in project robovm by robovm.

the class Properties method storeToXML.

/**
     * Writes all properties stored in this instance into the {@code
     * OutputStream} in XML representation. The DOCTYPE is
     *
     * <pre>
     * &lt;!DOCTYPE properties SYSTEM &quot;http://java.sun.com/dtd/properties.dtd&quot;&gt;
     * </pre>
     *
     * If the comment is null, no comment is added to the output. The parameter
     * {@code encoding} defines which encoding should be used. The {@code
     * OutputStream} is not closed at the end.
     *
     * @param os the {@code OutputStream} to write to.
     * @param comment the comment to add. If null, no comment is added.
     * @param encoding the code identifying the encoding that should be used to
     *            write into the {@code OutputStream}.
     * @throws IOException if an error occurs during writing to the output.
     */
public synchronized void storeToXML(OutputStream os, String comment, String encoding) throws IOException {
    if (os == null) {
        throw new NullPointerException("os == null");
    } else if (encoding == null) {
        throw new NullPointerException("encoding == null");
    }
    /*
         * We can write to XML file using encoding parameter but note that some
         * aliases for encodings are not supported by the XML parser. Thus we
         * have to know canonical name for encoding used to store data in XML
         * since the XML parser must recognize encoding name used to store data.
         */
    String encodingCanonicalName;
    try {
        encodingCanonicalName = Charset.forName(encoding).name();
    } catch (IllegalCharsetNameException e) {
        System.out.println("Warning: encoding name " + encoding + " is illegal, using UTF-8 as default encoding");
        encodingCanonicalName = "UTF-8";
    } catch (UnsupportedCharsetException e) {
        System.out.println("Warning: encoding " + encoding + " is not supported, using UTF-8 as default encoding");
        encodingCanonicalName = "UTF-8";
    }
    PrintStream printStream = new PrintStream(os, false, encodingCanonicalName);
    printStream.print("<?xml version=\"1.0\" encoding=\"");
    printStream.print(encodingCanonicalName);
    printStream.println("\"?>");
    printStream.print("<!DOCTYPE properties SYSTEM \"");
    printStream.print(PROP_DTD_NAME);
    printStream.println("\">");
    printStream.println("<properties>");
    if (comment != null) {
        printStream.print("<comment>");
        printStream.print(substitutePredefinedEntries(comment));
        printStream.println("</comment>");
    }
    for (Map.Entry<Object, Object> entry : entrySet()) {
        String keyValue = (String) entry.getKey();
        String entryValue = (String) entry.getValue();
        printStream.print("<entry key=\"");
        printStream.print(substitutePredefinedEntries(keyValue));
        printStream.print("\">");
        printStream.print(substitutePredefinedEntries(entryValue));
        printStream.println("</entry>");
    }
    printStream.println("</properties>");
    printStream.flush();
}
Also used : IllegalCharsetNameException(java.nio.charset.IllegalCharsetNameException) PrintStream(java.io.PrintStream) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException)

Aggregations

IllegalCharsetNameException (java.nio.charset.IllegalCharsetNameException)69 UnsupportedCharsetException (java.nio.charset.UnsupportedCharsetException)44 Charset (java.nio.charset.Charset)34 IOException (java.io.IOException)13 UnsupportedEncodingException (java.io.UnsupportedEncodingException)10 File (java.io.File)9 ByteBuffer (java.nio.ByteBuffer)7 ByteArrayInputStream (java.io.ByteArrayInputStream)6 InputStream (java.io.InputStream)6 CharacterCodingException (java.nio.charset.CharacterCodingException)6 CoreException (org.eclipse.core.runtime.CoreException)6 IStatus (org.eclipse.core.runtime.IStatus)6 Status (org.eclipse.core.runtime.Status)6 HistoricallyNamedCharset (sun.nio.cs.HistoricallyNamedCharset)6 CharsetEncoder (java.nio.charset.CharsetEncoder)5 UnmappableCharacterException (java.nio.charset.UnmappableCharacterException)5 SequenceInputStream (java.io.SequenceInputStream)4 XmlPullParserException (org.codehaus.plexus.util.xml.pull.XmlPullParserException)4 CharArrayWriter (java.io.CharArrayWriter)3 FileInputStream (java.io.FileInputStream)3