下面列出了怎么用java.io.CharConversionException的API类实例代码及写法,或者点击链接到github查看源代码。
public int read(char buf [], int offset, int len) throws IOException {
int i, c;
if (instream == null)
return -1;
for (i = 0; i < len; i++) {
if (start >= finish) {
start = 0;
finish = instream.read(buffer, 0, buffer.length);
if (finish <= 0) {
if (finish <= 0)
this.close();
break;
}
}
c = buffer[start++];
if ((c & 0x80) != 0)
throw new CharConversionException("Illegal ASCII character, 0x"
+ Integer.toHexString(c & 0xff));
buf[offset + i] = (char) c;
}
if (i == 0 && finish <= 0)
return -1;
return i;
}
public int read(char buf [], int offset, int len) throws IOException {
int i, c;
if (instream == null)
return -1;
for (i = 0; i < len; i++) {
if (start >= finish) {
start = 0;
finish = instream.read(buffer, 0, buffer.length);
if (finish <= 0) {
if (finish <= 0)
this.close();
break;
}
}
c = buffer[start++];
if ((c & 0x80) != 0)
throw new CharConversionException("Illegal ASCII character, 0x"
+ Integer.toHexString(c & 0xff));
buf[offset + i] = (char) c;
}
if (i == 0 && finish <= 0)
return -1;
return i;
}
@Messages("ERR_Coord_breaks_pom=Error: Group Id or Artifact Id would invalidate Maven POM xml file.")
private boolean checkCoord(JTextField field) {
String coord = field.getText();
boolean result = false;
try {
String escaped = XMLUtil.toAttributeValue(coord);
result = escaped.length() == coord.length() && coord.indexOf(">") == -1
&& coord.indexOf(" ") == -1;
} catch (CharConversionException ex) {
// ignore this one
}
if (result) {
result = !containsMultiByte(coord);
} else {
category.setErrorMessage(ERR_Coord_breaks_pom());
}
if (result) {
category.setErrorMessage(null);
}
return result;
}
/**
* Set the list of unchecked items to memorize.
*
* @param items the items to memorize.
* @throws CharConversionException if an error occurs while setting the list from the file (invalid characters).
* @throws InfinitiveLoopException if an error occurs while setting the list from the file (file parsing error).
*/
@SuppressWarnings("Duplicates")
public void setUncheckedItems(List<String> items)
throws CharConversionException,
InfinitiveLoopException {
List<String> prevItems = getUncheckedItems();
if (!prevItems.containsAll(items) || !items.containsAll(prevItems)) {
updated = true;
StringBuilder buffer = new StringBuilder(512);
boolean first = true;
for (String item : items) {
if (first) {
buffer.append(item);
} else {
buffer.append('\"').append(item);
}
first = false;
}
ini.setKeyValue(CONFIG_UNCHECKED_REDIST_ITEMS, CONFIG_UNCHECKED_REDIST_ITEMS__ITEM_LIST, buffer.toString());
}
}
@Override
public String getHtmlDisplayName () {
final Pair<String,JavaPlatform> platHolder = pp.getPlatform();
if (platHolder == null) {
return null;
}
final JavaPlatform jp = platHolder.second();
if (jp == null || !jp.isValid()) {
String displayName = this.getDisplayName();
try {
displayName = XMLUtil.toElementContent(displayName);
} catch (CharConversionException ex) {
// OK, no annotation in this case
return null;
}
return "<font color=\"#A40000\">" + displayName + "</font>"; //NOI18N
} else {
return null;
}
}
static String escape(String s) {
if (s != null) {
//unescape unicode sequences first (would be better if Pretty would not print them, but that might be more difficult):
Matcher matcher = UNICODE_SEQUENCE.matcher(s);
if (matcher.find()) {
StringBuilder result = new StringBuilder();
int lastReplaceEnd = 0;
do {
result.append(s.substring(lastReplaceEnd, matcher.start()));
int ch = Integer.parseInt(matcher.group(1), 16);
result.append((char) ch);
lastReplaceEnd = matcher.end();
} while (matcher.find());
result.append(s.substring(lastReplaceEnd));
s = result.toString();
}
try {
return XMLUtil.toAttributeValue(s);
} catch (CharConversionException ex) {
}
}
return null;
}
public static String target2String(TypeElement target) {
final Name qualifiedName = target.getQualifiedName(); //#130759
if (qualifiedName == null) {
Logger.getLogger(Utilities.class.getName()).warning("Target qualified name could not be resolved."); //NOI18N
return ""; //NOI18N
} else {
String qnString = qualifiedName.toString();
if (qnString.length() == 0) {
//probably an anonymous class
qnString = target.asType().toString();
}
try {
qnString = XMLUtil.toElementContent(qnString);
} catch (CharConversionException ex) {
Logger.getLogger(Utilities.class.getName()).log(Level.FINE, null, ex);
}
return qnString;
}
}
/**
* Append part of line that is before matched text.
*
* @param text Buffer to append to.
* @param prefixStart Line index of the first character to be displayed.
* @param matchStart Line index of the matched text.
* @param trim Skip leading whitespace characters.
*/
private void appendMarkedTextPrefix(StringBuilder text, int prefixStart,
int matchStart, boolean trim) throws CharConversionException {
int first = 0; // index of first non-whitespace character
if (trim) {
CharSequence lineText = txtDetail.getLineText();
while (first < matchStart && lineText.charAt(first) <= '\u0020') {
first++;
}
}
if (prefixStart > 0 && first < prefixStart) {
text.append(ELLIPSIS);
}
text.append(escape(txtDetail.getLineTextPart(
Math.max(prefixStart, first), matchStart)));
}
/**
* Writes a <code>String</code> to the client, without a carriage
* return-line feed (CRLF) character at the end.
*
* @param s
* the <code>String</code> to send to the client
* @exception IOException
* if an input or output exception occurred
*/
public void print(String s) throws IOException {
if (s == null)
s = "null";
int len = s.length();
for (int i = 0; i < len; i++) {
char c = s.charAt(i);
//
// XXX NOTE: This is clearly incorrect for many strings,
// but is the only consistent approach within the current
// servlet framework. It must suffice until servlet output
// streams properly encode their output.
//
if ((c & 0xff00) != 0) { // high order byte must be zero
String errMsg = lStrings.getString("err.not_iso8859_1");
Object[] errArgs = new Object[1];
errArgs[0] = Character.valueOf(c);
errMsg = MessageFormat.format(errMsg, errArgs);
throw new CharConversionException(errMsg);
}
write(c);
}
}
@Override
protected String messageHtmlName() {
if (! obj.isValid()) {
return null;
}
String name = obj.getNodeDelegate().getHtmlDisplayName();
if (name == null) {
try {
name = XMLUtil.toElementContent(obj.getNodeDelegate().getDisplayName());
} catch (CharConversionException ex) {
return null;
}
}
return annotateName(name, true, isModified(), !obj.getPrimaryFile().canWrite());
}
private JComponent createDetails( String text, ActionListener action ) {
if( null == action ) {
return new JLabel(text);
}
try {
text = "<html><u>" + XMLUtil.toElementContent(text); //NOI18N
} catch( CharConversionException ex ) {
throw new IllegalArgumentException(ex);
}
JButton btn = new JButton(text);
btn.setFocusable(false);
btn.setBorder(BorderFactory.createEmptyBorder());
btn.setBorderPainted(false);
btn.setFocusPainted(false);
btn.setOpaque(false);
btn.setContentAreaFilled(false);
btn.addActionListener(action);
btn.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
Color c = UIManager.getColor("nb.html.link.foreground"); //NOI18N
if (c != null) {
btn.setForeground(c);
}
return btn;
}
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
String text;
if (value == UIUtil.WAIT_VALUE) {
text = UIUtil.WAIT_VALUE;
} else if (value == INVALID_PLATFORM) {
text = INVALID_PLATFORM;
renderer.setHtml(true);
} else {
ModuleDependency md = (ModuleDependency) value;
// XXX the following is wrong; spec requires additional logic:
boolean bold = boldfaceApiModules && md.getModuleEntry().getPublicPackages().length > 0;
boolean deprecated = md.getModuleEntry().isDeprecated();
renderer.setHtml(bold || deprecated);
String locName = md.getModuleEntry().getLocalizedName();
text = locName;
if (bold || deprecated) {
try {
text = "<html>" + (bold ? "<b>" : "") + (deprecated ? "<s>" : "") + XMLUtil.toElementContent(locName); // NOI18N
} catch (CharConversionException e) {
// forget it
}
}
}
return renderer.getListCellRendererComponent(list, text, index, isSelected, cellHasFocus);
}
private List<Redist> getRedistPatternsAndDesc(String configKey)
throws CharConversionException,
InfinitiveLoopException {
List<Redist> redistList = new ArrayList<>(8);
List<String> redistTokens = new ArrayList<>(64);
for (Ini singleIni : inis) {
String[] tokens = singleIni.getKeyValue("", CONFIG_REDIST_PATTERNS, configKey).split("\"", 0);
redistTokens.addAll(Arrays.asList(tokens));
}
boolean FileDescToggle = true;
String redistName = null;
String redtsiDescription;
for (String redist : redistTokens) {
if (redist.length() > 0) { // Skip first and last tokens.
if (FileDescToggle) {
redistName = redist;
} else {
redtsiDescription = redist;
redistList.add(new Redist(redistName, redtsiDescription));
}
FileDescToggle ^= true;
}
}
return redistList;
}
@Override
public String getHtmlDisplayName() {
final Pair<String, JavaPlatform> platHolder = pp.getPlatform();
if (platHolder == null) {
return null;
}
final JavaPlatform jp = platHolder.second();
if (jp == null || !jp.isValid()) {
String displayName = this.getDisplayName();
try {
displayName = XMLUtil.toElementContent(displayName);
} catch (CharConversionException ex) {
// OK, no annotation in this case
return null;
}
return "<font color=\"#A40000\">" + displayName + "</font>"; //NOI18N
} else {
return null;
}
}
private JComponent createDetails(String text, ActionListener action) {
try {
text = (action == null ? "<html>" : "<html><a href=\"_blank\">") + XMLUtil.toElementContent(text); //NOI18N
} catch (CharConversionException ex) {
throw new IllegalArgumentException(ex);
}
if (null == action) {
return new JLabel(text);
}
JButton btn = new JButton(text);
btn.setFocusable(false);
btn.setBorder(BorderFactory.createEmptyBorder());
btn.setBorderPainted(false);
btn.setFocusPainted(false);
btn.setOpaque(false);
btn.setContentAreaFilled(false);
btn.addActionListener(action);
btn.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
Color c = UIManager.getColor("nb.html.link.foreground"); //NOI18N
if (c != null) {
btn.setForeground(c);
}
return btn;
}
public @Override String getHtmlDisplayName() {
String htmlName = getOriginal().getHtmlDisplayName();
if (htmlName == null) {
try {
htmlName = XMLUtil.toElementContent(getOriginal().getDisplayName());
} catch (CharConversionException ex) {
// ignore
}
}
if (htmlName == null) {
return null;
}
if (files != null && files.iterator().hasNext()) {
try {
String annotatedMagic = files.iterator().next().getFileSystem().
getDecorator().annotateNameHtml(MAGIC, files);
if (annotatedMagic != null) {
htmlName = annotatedMagic.replace(MAGIC, htmlName);
}
} catch (FileStateInvalidException e) {
LOG.log(Level.INFO, null, e);
}
}
return isMainAsync()? "<b>" + htmlName + "</b>" : htmlName;
}
@Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
AnalyzerFactory a = (AnalyzerFactory) value;
String text = SPIAccessor.ACCESSOR.getAnalyzerDisplayName(a);
boolean isErroneous;
synchronized (errors) {
isErroneous = errors.containsKey(a);
}
if (isErroneous) {
try {
text = "<html><font color='ref'>" + XMLUtil.toElementContent(text);
} catch (CharConversionException ex) {
LOG.log(Level.FINE, null, ex);
}
}
return super.getListCellRendererComponent(list, text, index, isSelected, cellHasFocus);
}
/**
* Writes a <code>String</code> to the client,
* without a carriage return-line feed (CRLF)
* character at the end.
*
*
* @param s the <code>String</code> to send to the client
*
* @exception IOException if an input or output exception occurred
*
*/
public void print(String s) throws IOException {
if (s==null) s="null";
int len = s.length();
for (int i = 0; i < len; i++) {
char c = s.charAt (i);
//
// XXX NOTE: This is clearly incorrect for many strings,
// but is the only consistent approach within the current
// servlet framework. It must suffice until servlet output
// streams properly encode their output.
//
if ((c & 0xff00) != 0) { // high order byte must be zero
String errMsg = lStrings.getString("err.not_iso8859_1");
Object[] errArgs = new Object[1];
errArgs[0] = new Character(c);
errMsg = MessageFormat.format(errMsg, errArgs);
throw new CharConversionException(errMsg);
}
write (c);
}
}
public List<String> getPossibleSteamFolders()
throws CharConversionException,
InfinitiveLoopException {
String folderList = ini.getKeyValue("/", CONFIG_STEAM_FOLDERS, CONFIG_STEAM_FOLDERS__POSSIBLE_DIRS);
String[] patterns = folderList.split(Matcher.quoteReplacement(";"), 0);
List<String> allSteamPaths = new ArrayList<>(80);
File[] roots = File.listRoots();
String[] driveLetters = new String[roots.length];
for (int nRoot = 0; nRoot < roots.length; nRoot++) {
driveLetters[nRoot] = roots[nRoot].getAbsolutePath();
}
String varDriveLetter = /* Matcher.quoteReplacement( */ "{drive_letter}"/* ) */;
for (String basePattern : patterns) {
for (String driveLetter : driveLetters) {
allSteamPaths.add(basePattern.replace(varDriveLetter, driveLetter));
}
}
Collections.addAll(allSteamPaths, patterns);
return allSteamPaths;
}
public HudsonJobBuildNode(HudsonJobBuild build) {
super(makeChildren(build), Lookups.singleton(build));
setName(Integer.toString(build.getNumber()));
setDisplayName(NbBundle.getMessage(HudsonJobBuildNode.class, "HudsonJobBuildNode.displayName", build.getNumber()));
Color effectiveColor;
if (build.isBuilding()) {
effectiveColor = build.getJob().getColor();
} else {
effectiveColor = Utilities.getColorForBuild(build);
}
try {
htmlDisplayName = effectiveColor.colorizeDisplayName(XMLUtil.toElementContent(getDisplayName()));
} catch (CharConversionException x) {
htmlDisplayName = null;
}
setIconBaseWithExtension(effectiveColor.iconBase());
this.build = build;
}
/**
* Writes a <code>String</code> to the client, without a carriage
* return-line feed (CRLF) character at the end.
*
* @param s
* the <code>String</code> to send to the client
* @exception IOException
* if an input or output exception occurred
*/
public void print(String s) throws IOException {
if (s == null)
s = "null";
int len = s.length();
for (int i = 0; i < len; i++) {
char c = s.charAt(i);
//
// XXX NOTE: This is clearly incorrect for many strings,
// but is the only consistent approach within the current
// servlet framework. It must suffice until servlet output
// streams properly encode their output.
//
if ((c & 0xff00) != 0) { // high order byte must be zero
String errMsg = lStrings.getString("err.not_iso8859_1");
Object[] errArgs = new Object[1];
errArgs[0] = Character.valueOf(c);
errMsg = MessageFormat.format(errMsg, errArgs);
throw new CharConversionException(errMsg);
}
write(c);
}
}
public int read(char buf [], int offset, int len) throws IOException {
int i, c;
if (instream == null)
return -1;
for (i = 0; i < len; i++) {
if (start >= finish) {
start = 0;
finish = instream.read(buffer, 0, buffer.length);
if (finish <= 0) {
if (finish <= 0)
this.close();
break;
}
}
c = buffer[start++];
if ((c & 0x80) != 0)
throw new CharConversionException("Illegal ASCII character, 0x"
+ Integer.toHexString(c & 0xff));
buf[offset + i] = (char) c;
}
if (i == 0 && finish <= 0)
return -1;
return i;
}
/**
* Writes a <code>String</code> to the client, without a carriage
* return-line feed (CRLF) character at the end.
*
* @param s
* the <code>String</code> to send to the client
* @exception IOException
* if an input or output exception occurred
*/
public void print(String s) throws IOException {
if (s == null) {
s = "null";
}
int len = s.length();
byte[] buffer = new byte[len];
for (int i = 0; i < len; i++) {
char c = s.charAt(i);
//
// XXX NOTE: This is clearly incorrect for many strings,
// but is the only consistent approach within the current
// servlet framework. It must suffice until servlet output
// streams properly encode their output.
//
if ((c & 0xff00) != 0) { // high order byte must be zero
String errMsg = lStrings.getString("err.not_iso8859_1");
Object[] errArgs = new Object[1];
errArgs[0] = Character.valueOf(c);
errMsg = MessageFormat.format(errMsg, errArgs);
throw new CharConversionException(errMsg);
}
buffer[i] = (byte) (c & 0xFF);
}
write(buffer);
}
/**
* Detect the validation mode for the XML document in the supplied {@link InputStream}.
* Note that the supplied {@link InputStream} is closed by this method before returning.
* @param inputStream the InputStream to parse
* @throws IOException in case of I/O failure
* @see #VALIDATION_DTD
* @see #VALIDATION_XSD
*/
public int detectValidationMode(InputStream inputStream) throws IOException {
// Peek into the file to look for DOCTYPE.
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
boolean isDtdValidated = false;
String content;
while ((content = reader.readLine()) != null) {
content = consumeCommentTokens(content);
if (this.inComment || !StringUtils.hasText(content)) {
continue;
}
if (hasDoctype(content)) {
isDtdValidated = true;
break;
}
if (hasOpeningTag(content)) {
// End of meaningful data...
break;
}
}
return (isDtdValidated ? VALIDATION_DTD : VALIDATION_XSD);
}
catch (CharConversionException ex) {
// Choked on some character encoding...
// Leave the decision up to the caller.
return VALIDATION_AUTO;
}
finally {
reader.close();
}
}
/**
* Detect the validation mode for the XML document in the supplied {@link InputStream}.
* Note that the supplied {@link InputStream} is closed by this method before returning.
* @param inputStream the InputStream to parse
* @throws IOException in case of I/O failure
* @see #VALIDATION_DTD
* @see #VALIDATION_XSD
*/
public int detectValidationMode(InputStream inputStream) throws IOException {
// Peek into the file to look for DOCTYPE.
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
boolean isDtdValidated = false;
String content;
while ((content = reader.readLine()) != null) {
content = consumeCommentTokens(content);
if (this.inComment || !StringUtils.hasText(content)) {
continue;
}
if (hasDoctype(content)) {
isDtdValidated = true;
break;
}
if (hasOpeningTag(content)) {
// End of meaningful data...
break;
}
}
return (isDtdValidated ? VALIDATION_DTD : VALIDATION_XSD);
}
catch (CharConversionException ex) {
// Choked on some character encoding...
// Leave the decision up to the caller.
return VALIDATION_AUTO;
}
finally {
reader.close();
}
}
public void methodThrowExceptions() throws CharConversionException, FileSystemException, IOException {
int i = (int) (Math.random() * 3);
if (i == 0)
throw new CharConversionException();
if (i == 1)
throw new FileSystemException("");
if (i == 2)
throw new IOException();
}
private String escapeAttrValue(String attrValue) {
try {
return XMLUtil.toAttributeValue(attrValue);
} catch (CharConversionException e) {
return null;
}
}
/**
* Store the list of unchecked items (redistributable packages shown in the main table) to a configuration file.
*/
private void memorizeUncheckedItemsToConf() {
try {
if (fSteamDir != null) {
List<String> nowUncheckedItemsList = new ArrayList<>(8);
List<String> nowCheckedItemsList = new ArrayList<>(8);
List<String> newUncheckedItemsList = new ArrayList<>(8);
List<String> prevUncheckedItems = uncheckedItems.getUncheckedItems();
for (int row = 0; row < model.getRowCount(); row++) {
boolean checked = (Boolean) model.getValueAt(row, 0);
String redistFullPath = (String) model.getValueAt(row, 1);
if (checked) {
nowCheckedItemsList.add(redistFullPath);
} else {
nowUncheckedItemsList.add(redistFullPath);
}
}
newUncheckedItemsList.addAll(nowUncheckedItemsList);
for (String prevUncheckedItem : prevUncheckedItems) {
if (!nowCheckedItemsList.contains(prevUncheckedItem) && !newUncheckedItemsList.contains(prevUncheckedItem)) {
newUncheckedItemsList.add(prevUncheckedItem);
}
}
uncheckedItems.setUncheckedItems(newUncheckedItemsList);
}
} catch (CharConversionException | InfinitiveLoopException ex) {
Log.error(ex);
}
}
public @Override String getHtmlDisplayName() {
if (!project.isMavenProjectLoaded()) {
return null;
}
String packaging = project.getOriginalMavenProject().getPackaging();
if (project.getLookup().lookup(SpecialIcon.class) != null) {
return null;
}
try {
return XMLUtil.toElementContent(getDisplayName()) + " <font color='!controlShadow'>" + packaging + "</font>";
} catch (CharConversionException x) {
return null;
}
}
static String escape(String s) {
if (s != null) {
try {
return XMLUtil.toAttributeValue(s);
} catch (CharConversionException ex) {
}
}
return null;
}