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);
}
}
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;
}
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;
}
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;
}
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>
* <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
* </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();
}
Aggregations