下面列出了怎么用org.openide.util.Exceptions的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public TemplateModel getSharedVariable(String string) {
Object value = map.getAttribute(string);
if (value == null) {
value = engineScope.get(string);
}
if (value == null && fo != null) {
value = fo.getAttribute(string);
}
try {
return getObjectWrapper().wrap(value);
} catch (TemplateModelException ex) {
Exceptions.printStackTrace(ex);
return null;
}
}
/**
* when ever there is need for non-java files creation or lookup,
* use this method to get the right location for all projects.
* Eg. maven places resources not next to the java files.
* Please note that the method should not be used for
* checking file existence. There can be multiple resource roots, the returned one
* is just the first in line. Use <code>getResource</code> instead in that case.
* @param project
* @return
*/
public static FileObject getResourceDirectory(Project project) {
Sources srcs = ProjectUtils.getSources(project);
SourceGroup[] sourceGroups = srcs.getSourceGroups(JavaProjectConstants.SOURCES_TYPE_RESOURCES);
if (sourceGroups != null && sourceGroups.length > 0) {
return sourceGroups[0].getRootFolder();
}
try {
return project.getProjectDirectory()
.getFileObject("src/main")
.createFolder("resources");
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
return null;
}
}
@NonNull
private static Properties loadRelocation(
@NonNull final File cacheRoot) {
final Properties result = new Properties();
final File relocationFile = new File (cacheRoot, RELOCATION_FILE);
if (relocationFile.canRead()) {
try {
final FileInputStream in = new FileInputStream(relocationFile);
try {
result.load(in);
} finally {
in.close();
}
} catch (IOException ioe) {
Exceptions.printStackTrace(ioe);
}
}
return result;
}
private static void updateCleaner(final RequestProcessor.Task task) {
if(CLEAN_TASK != null) {
CLEAN_TASK.cancel();
}
CLEAN_TASK = new CleanTask(task);
final CancellableTask cleanTask = CLEAN_TASK;
RP.post(new Runnable() {
@Override
public void run() {
try {
cleanTask.run(null);
} catch (Exception ex) {
Exceptions.printStackTrace(ex);
}
}
});
}
@Override
public List<? extends CodeGenerator> create(Lookup context) {
ArrayList<CodeGenerator> ret = new ArrayList<CodeGenerator>();
JTextComponent component = context.lookup(JTextComponent.class);
CompilationController controller = context.lookup(CompilationController.class);
TreePath path = context.lookup(TreePath.class);
path = path != null ? SendEmailCodeGenerator.getPathElementOfKind(TreeUtilities.CLASS_TREE_KINDS, path) : null;
if (component == null || controller == null || path == null)
return ret;
try {
controller.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
Element elem = controller.getTrees().getElement(path);
if (elem != null) {
SendJMSMessageCodeGenerator gen = createSendJMSMessageAction(component, controller, elem);
if (gen != null)
ret.add(gen);
}
} catch (IOException ioe) {
Exceptions.printStackTrace(ioe);
}
return ret;
}
@Override
public void handleError(String msg, Throwable t) {
progressHandle.finish();
if (msg == null) {
return;
}
if (!started) {
SceneViewerTopComponent.showOpenGLError(msg);
Exceptions.printStackTrace(t);
} else {
if (lastError != null && !lastError.equals(msg)) {
Message mesg = new NotifyDescriptor.Message(
"Error in scene!\n"
+ "(" + t + ")",
NotifyDescriptor.WARNING_MESSAGE);
DialogDisplayer.getDefault().notifyLater(mesg);
Exceptions.printStackTrace(t);
lastError = msg;
}
}
}
public String[] getEnumeratedValues(Class<?> c) {
if (EnumeratedAttribute.class.isAssignableFrom(c)) {
try {
return ((EnumeratedAttribute)c.newInstance()).getValues();
} catch (Exception e) {
AntModule.err.notify(ErrorManager.INFORMATIONAL, e);
}
} else if (Enum.class.isAssignableFrom(c)) { // Ant 1.7.0 (#41058)
try {
Enum<?>[] vals = (Enum<?>[]) c.getMethod("values").invoke(null);
String[] names = new String[vals.length];
for (int i = 0; i < vals.length; i++) {
names[i] = vals[i].name();
}
return names;
} catch (Exception x) {
Exceptions.printStackTrace(x);
}
}
return null;
}
public NodeList createNodes(Project project) {
// this.proj = project;
//If our item is in the project's lookup,
//return a new node in the node list:
ImportantFilesLookupItem item = project.getLookup().lookup(ImportantFilesLookupItem.class);
if (item != null) {
try {
ImportantFilesNode nd = new ImportantFilesNode(project);
return NodeFactorySupport.fixedNodeList(nd);
} catch (DataObjectNotFoundException ex) {
Exceptions.printStackTrace(ex);
}
}
//If our item isn't in the lookup,
//then return an empty list of nodes:
return NodeFactorySupport.fixedNodeList();
}
public int acceptClient() {
ensureStarted();
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
Socket client = socket.accept();
MessageDispatcherImpl dispatcher = new MessageDispatcherImpl();
Transport transport = new Transport(client, dispatcher);
WebKitDebugging webKit = Factory.createWebKitDebugging(transport);
Lookup context = Lookups.fixed(transport, webKit, dispatcher);
PageInspector.getDefault().inspectPage(context);
} catch (IOException ioex) {
Exceptions.printStackTrace(ioex);
}
}
});
t.start();
return socket.getLocalPort();
}
@Override
protected int waitResultImpl() throws InterruptedException {
if (streams == null || streams.channel == null) {
return -1;
}
try {
while (streams.channel.isConnected()) {
Thread.sleep(200);
}
finishing();
return streams.channel.getExitStatus();
} finally {
if (streams != null) {
try {
ConnectionManagerAccessor.getDefault().closeAndReleaseChannel(getExecutionEnvironment(), streams.channel);
} catch (JSchException ex) {
Exceptions.printStackTrace(ex);
}
}
}
}
@Override
protected boolean delegates(JTextComponent target, PositionRegion region, int pos) {
if (super.delegates(target, region, pos)) {
return true;
}
LineDocument ld = LineDocumentUtils.as(target.getDocument(), LineDocument.class);
if (ld == null) {
return true;
}
try {
int end = LineDocumentUtils.getLineEnd(ld, region.getStartOffset());
// delegate for all but the first line
return pos > end;
} catch (BadLocationException ex) {
Exceptions.printStackTrace(ex);
return true;
}
}
private EditCookie getEditorCookie(Document doc, int offset) {
TokenHierarchy<?> th = TokenHierarchy.get(doc);
TokenSequence ts = th.tokenSequence(Language.find("text/x-manifest"));
if (ts == null)
return null;
ts.move(offset);
if (!ts.moveNext())
return null;
Token t = ts.token();
FileObject fo = getFileObject(doc);
String name = t.toString();
FileObject props = findFile(fo, name);
if (props != null) {
try {
DataObject dobj = DataObject.find(props);
return dobj.getLookup().lookup(EditCookie.class);
} catch (DataObjectNotFoundException ex) {
Exceptions.printStackTrace(ex);
}
}
return null;
}
/**
* Replace the content of the document by the graph.
*/
private void replaceDocument(final StyledDocument doc, T graph) {
final ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
graph.write(out);
} catch (IOException ioe) {
Exceptions.printStackTrace(ioe);
}
NbDocument.runAtomic(doc, new Runnable() {
public void run() {
try {
doc.remove(0, doc.getLength());
doc.insertString(0, out.toString(), null);
} catch (BadLocationException ble) {
Exceptions.printStackTrace(ble);
}
}
});
}
public void actionPerformed(ActionEvent evt, final JTextComponent target) {
Document doc = target.getDocument();
doc.render(new Runnable() {
@Override
public void run() {
FoldHierarchy hierarchy = FoldHierarchy.get(target);
int dot = target.getCaret().getDot();
hierarchy.lock();
try {
try {
int rowStart = javax.swing.text.Utilities.getRowStart(target, dot);
int rowEnd = javax.swing.text.Utilities.getRowEnd(target, dot);
Fold fold = getLineFold(hierarchy, dot, rowStart, rowEnd);
if (fold != null) {
hierarchy.expand(fold);
}
} catch (BadLocationException ble) {
Exceptions.printStackTrace(ble);
}
} finally {
hierarchy.unlock();
}
}
});
}
public void execute(Diagram d, String code) {
try {
Bindings b = bindings;
b.put("graph", d);
engine.eval(code, b);
} catch (ScriptException ex) {
Exceptions.printStackTrace(ex);
}
}
public void markModified() throws java.io.IOException {
if (cannotBeModified != null) {
IOException e = new IOException ();
Exceptions.attachLocalizedMessage(e, cannotBeModified);
throw e;
}
modified = true;
}
public void contextInit(Context ctx) throws TomcatException {
if( ctx.getDebug() > 0 ) ctx.log("NbServletsInterceptor - init " + ctx.getPath() + " " + ctx.getDocBase() ); // NOI18N
ContextManager cm=ctx.getContextManager();
try {
// Default init
addNbServlets( ctx );
} catch (Exception e) {
Exceptions.attachMessage(e, "NbServletsInterceptor failed"); // NOI18N
Logger.getLogger("global").log(Level.INFO, null, e);
}
}
public boolean addToHierarchy(Fold fold, FoldHierarchyTransactionImpl transaction) {
checkFoldOperation(fold);
try {
execution.incModCount();
return execution.add(fold, transaction);
} catch (HierarchyErrorException ex) {
try {
rebuildHierarchy(ex);
return execution.add(fold, transaction);
} catch (HierarchyErrorException ex2) {
Exceptions.printStackTrace(ex2);
return false;
}
}
}
@Override
public String getShortDescription() {
String res = descCache.get();
if (res == null) {
RP.execute(() -> {
try {
SourceForBinaryQuery.Result2 sfbq = resCache.get();
if (sfbq == null) {
sfbq = SourceForBinaryQuery.findSourceRoots2(uri.toURL());
if (resCache.compareAndSet(null, sfbq)) {
sfbq.addChangeListener(WeakListeners.change(this, sfbq));
} else {
sfbq = resCache.get();
}
}
descCache.set(Arrays.stream(sfbq.getRoots())
.map(ModuleNode::getModuleFolder)
.map(FileUtil::getFileDisplayName)
.collect(Collectors.joining(File.pathSeparator)));
fireShortDescriptionChange(null, null);
} catch (MalformedURLException ex) {
Exceptions.printStackTrace(ex);
}
});
}
return res;
}
/**
* Set the default font size as a preference if its not already defined.
* <p>
* Top Components listen for changes in
* ApplicationPreferenceKeys.OUTPUT2_PREFERENCE and if its not defined then
* the listener will not be registered. This initialise method is called
* when the application starts to make sure a preference is defined.
*/
public static synchronized void initialiseFontPreferenceOnFirstUse() {
final Preferences p = NbPreferences.root();
try {
if (!p.nodeExists(ApplicationPreferenceKeys.OUTPUT2_PREFERENCE)) {
p.node(ApplicationPreferenceKeys.OUTPUT2_PREFERENCE).put(ApplicationPreferenceKeys.OUTPUT2_FONT_SIZE, ApplicationPreferenceKeys.OUTPUT2_FONT_SIZE_DEFAULT);
}
} catch (final BackingStoreException ex) {
Exceptions.printStackTrace(ex);
}
}
private void saveAll(Node[] activatedNodes) {
for(Node node : activatedNodes) {
SaveCookie saveCookie = node.getLookup().lookup(SaveCookie.class);
if (saveCookie != null) {
try {
saveCookie.save();
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
}
}
}
private void learnMoreLabelMousePressed(MouseEvent evt) {//GEN-FIRST:event_learnMoreLabelMousePressed
try {
URL url = new URL("https://framework.zend.com/learn"); // NOI18N
HtmlBrowser.URLDisplayer.getDefault().showURL(url);
} catch (MalformedURLException ex) {
Exceptions.printStackTrace(ex);
}
}
/**
* Returns line index (line number - 1) of the package statement or {@literal -1}
* if no package statement was found within this in {@link BaseDocument}.
*
* @param doc document
* @return line index (line number - 1) of the package statement or {@literal -1}
* if no package statement was found within this {@link BaseDocument}.
*/
private static int getPackageLineIndex(BaseDocument doc) {
try {
int lastPackageOffset = getLastPackageStatementOffset(doc);
if (lastPackageOffset != -1) {
return Utilities.getLineOffset(doc, lastPackageOffset);
}
} catch (BadLocationException ex) {
Exceptions.printStackTrace(ex);
}
return -1;
}
public static String readFromStream(InputStream stream) {
try {
return IOUtils.toString(stream);
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
} finally {
IOUtils.closeQuietly(stream);
}
return null;
}
private static void filterProjectXML(FileObject fo, ZipInputStream str, String name) throws IOException {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
FileUtil.copy(str, baos);
Document doc = XMLUtil.parse(new InputSource(new ByteArrayInputStream(baos.toByteArray())), false, false, null, null);
NodeList nl = doc.getDocumentElement().getElementsByTagName("name");
if (nl != null) {
for (int i = 0; i < nl.getLength(); i++) {
Element el = (Element) nl.item(i);
if (el.getParentNode() != null && "data".equals(el.getParentNode().getNodeName())) {
NodeList nl2 = el.getChildNodes();
if (nl2.getLength() > 0) {
nl2.item(0).setNodeValue(name);
}
break;
}
}
}
OutputStream out = fo.getOutputStream();
try {
XMLUtil.write(doc, out, "UTF-8");
} finally {
out.close();
}
} catch (Exception ex) {
Exceptions.printStackTrace(ex);
writeFile(str, fo);
}
}
public MessageDestinationRef createDestinationRef() throws IOException {
try {
return (org.netbeans.modules.j2ee.dd.api.common.MessageDestinationRef) getWebApp().createBean("MessageDestinationRef");
} catch (ClassNotFoundException ex) {
Exceptions.printStackTrace(ex);
}
return null;
}
private void save() {
new RequestProcessor("R Scripts Saver").post(new Runnable() { // NOI18N
public void run() {
try {
Properties p = listToProperties(list());
ProfilerStorage.saveGlobalProperties(p, SAVED_R_QUERIES_FILENAME);
} catch (Exception e) {
ProfilerDialogs.displayError(Bundle.CustomRQueries_SaveFailed());
Exceptions.printStackTrace(e);
}
}
});
}
/**
* XML Generation.
*
* @param jacocoExecFile
* @param reportdir
* @param project
*/
public void myXmlReportGeneration(File jacocoExecFile, File reportdir, Project project) {
try {
reportGenerator = new JacocoNBModuleReportGenerator(jacocoExecFile, reportdir, true);
processProject(project);
reportGenerator.end();
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
}
public static CloneableEditorSupport findCloneableEditorSupport(FileObject fo) {
DataObject dob = null;
try {
dob = DataObject.find(fo);
} catch (DataObjectNotFoundException ex) {
Exceptions.printStackTrace(ex);
}
return dob == null ? null : RefactoringUtils.findCloneableEditorSupport(dob);
}
public String getHeaderField (String name) {
if ("content-type".equals(name)) { //NOI18N
try {
this.connect();
FileObject fo = FileUtil.toFileObject(f);
if (fo != null) {
return fo.getMIMEType();
}
} catch (IOException ioe) {
Exceptions.printStackTrace(ioe);
}
}
return super.getHeaderField(name);
}