Java Code Examples for org.openide.util.Exceptions#attachMessage()

The following examples show how to use org.openide.util.Exceptions#attachMessage() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MainProjectManager.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("DMI_COLLECTION_OF_URLS")
private static Set<URL> getProjectRoots(Project p) {
    Set<URL> projectRoots = new HashSet<URL>(); // roots
    Sources sources = ProjectUtils.getSources(p);
    SourceGroup[] sgs = sources.getSourceGroups("java"); // org.netbeans.api.java.project.JavaProjectConstants.SOURCES_TYPE_JAVA
    for (SourceGroup sg : sgs) {
        URL root;
        try {
            root = sg.getRootFolder().toURL();
            projectRoots.add(root);
        } catch (NullPointerException npe) {
            // http://www.netbeans.org/issues/show_bug.cgi?id=148076
            if (sg == null) {
                npe = Exceptions.attachMessage(npe, "Null source group returned from "+sources+" of class "+sources.getClass());
            } else if (sg.getRootFolder() == null) {
                npe = Exceptions.attachMessage(npe, "Null root folder returned from "+sg+" of class "+sg.getClass());
            }
            Exceptions.printStackTrace(npe);
        }
    }
    return projectRoots;
}
 
Example 2
Source File: OutputFileManager.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private File getClassFolderForSourceImpl (final URL sibling) throws IOException {
    List<ClassPath.Entry> entries = this.scp.entries();
    int eSize = entries.size();
    if ( eSize == 1) {
        return getClassFolder(entries.get(0).getURL());
    }
    if (eSize == 0) {
        return null;
    }
    try {
        for (ClassPath.Entry entry : entries) {
            URL rootUrl = entry.getURL();
            if (FileObjects.isParentOf(rootUrl, sibling)) {
                return getClassFolder(rootUrl);
            }
        }
    } catch (IllegalArgumentException e) {
        //Logging for issue #151416
        String message = String.format("uri: %s", sibling.toString());
        throw Exceptions.attachMessage(e, message);
    }
    return null;
}
 
Example 3
Source File: AnnotationTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void performAnnotationWrappingTest(final String annotationSpecification) throws Throwable {
    Map<String, List<String>> variables = new HashMap<String, List<String>>();

    variables.put(FmtOptions.wrapAnnotations, Arrays.asList(WrapStyle.WRAP_ALWAYS.name(), WrapStyle.WRAP_IF_LONG.name(), WrapStyle.WRAP_NEVER.name()));
    variables.put(FmtOptions.wrapAnnotationArgs, Arrays.asList(WrapStyle.WRAP_ALWAYS.name(), WrapStyle.WRAP_IF_LONG.name(), WrapStyle.WRAP_NEVER.name()));
    variables.put(FmtOptions.alignMultilineAnnotationArgs, Arrays.asList("false", "true"));
    variables.put(FmtOptions.indentSize, Arrays.asList("4", "5"));
    variables.put(FmtOptions.continuationIndentSize, Arrays.asList("6", "7"));

    List<Map<String, String>> variants = computeVariants(variables);

    for (Map<String, String> settings : variants) {
        try {
            performAnnotationWrappingTest(annotationSpecification, settings);
        } catch (Throwable t) {
            Exceptions.attachMessage(t, settings.toString());
            throw t;
        }
    }
}
 
Example 4
Source File: MainProjectManager.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("DMI_COLLECTION_OF_URLS")
private static Set<URL> getProjectRoots(Project p) {
    Set<URL> projectRoots = new HashSet<URL>(); // roots
    Sources sources = ProjectUtils.getSources(p);
    SourceGroup[] sgs = sources.getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA);
    for (SourceGroup sg : sgs) {
        URL root;
        try {
            root = sg.getRootFolder().toURL();
            projectRoots.add(root);
        } catch (NullPointerException npe) {
            // http://www.netbeans.org/issues/show_bug.cgi?id=148076
            if (sg == null) {
                npe = Exceptions.attachMessage(npe, "Null source group returned from "+sources+" of class "+sources.getClass());
            } else if (sg.getRootFolder() == null) {
                npe = Exceptions.attachMessage(npe, "Null root folder returned from "+sg+" of class "+sg.getClass());
            }
            Exceptions.printStackTrace(npe);
        }
    }
    return projectRoots;
}
 
Example 5
Source File: ExceptionsTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testAttachLocalizedMessageForWeirdException() {
    class WeirdEx extends Exception {
        public WeirdEx(String message) {
            super(message);
        }

        @Override
        public Throwable getCause() {
            return null;
        }
    }

    Exception e = new WeirdEx("Help");
    String msg = "me please";

    Exception expResult = e;
    Exception result = Exceptions.attachMessage(e, msg);
    assertEquals(expResult, result);

    String fnd = Exceptions.findLocalizedMessage(e);

    assertEquals("No localized msg found", null, fnd);

    assertCleanStackTrace(e);
}
 
Example 6
Source File: ExceptionsTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testAnnotateCNFE() {
    Exception e = new ClassNotFoundException();
    String msg = "text of annotation";

    MyHandler mh = new MyHandler();
    Exceptions.LOG.addHandler(mh);
    
    Exceptions.attachMessage(e, msg);
    Exceptions.printStackTrace(e);

    assertTrue(MyHandler.lastThrowable == e || MyHandler.lastThrowable.getCause() == e);
    
    StringWriter w = new StringWriter();
    MyHandler.lastThrowable.printStackTrace(new PrintWriter(w));
    String stackTrace = w.toString();

    if (!stackTrace.contains(msg)) fail("\'"+msg+"\' not found: "+stackTrace);
}
 
Example 7
Source File: AndroidDebugTransport.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void read(SelectionKey key, byte[] message, Integer dataType) {
    final String string;
    string = new String(message, Charset.forName("UTF-8")).trim(); //NOI18N
    try {
        final Object parse = JSONValue.parseWithException(string);
        if (callBack == null) {
            LOGGER.info("callBack is null. Ignoring response: " + string);
        } else {
            callBack.handleResponse(new Response((JSONObject) parse));
        }
    } catch (ParseException ex) {
        Exceptions.attachMessage(ex, string);
        Exceptions.printStackTrace(ex);
    }
}
 
Example 8
Source File: AbstractOutputPane.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public final void sendCaretToPos(int startPos, int endPos, boolean select) {
    inSendCaretToLine = true;
    try {
        getCaret().setVisible(true);
        getCaret().setSelectionVisible(true);
        if (select) {
            scrollTo(endPos);
            getCaret().setDot(endPos);
            getCaret().moveDot(startPos);
            textView.repaint();
        } else {
            getCaret().setDot(startPos);
        }
    } catch (Error sie) {
        if (sie.getClass().getName().equals("javax.swing.text.StateInvariantError")) {
            Exceptions.attachMessage(sie, "sendCaretToPos("+startPos+", "+endPos+", "+select+"), caret = "+getCaret()+", highlighter = "+textView.getHighlighter()+", document length = "+textView.getDocument().getLength());
        }
        Exceptions.printStackTrace(sie);
    } finally {
        locked = false;
        inSendCaretToLine = false;
    }
}
 
Example 9
Source File: InstallerTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testCreateMessageIssue160019() throws IOException {//ignore annotations
    final List<LogRecord> logs = new ArrayList<LogRecord>();
    ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream();
    Exception rootExc = new NullPointerException("root");
    Exceptions.attachMessage(rootExc, "annotation message");
    LogRecord rec = new LogRecord(Level.SEVERE, "test");
    rec.setThrown(rootExc);
    LogRecords.write(bos, rec);
    bos.close();
    ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    LogRecords.scan(bis, new Handler() {

        @Override
        public void publish(LogRecord record) {
            logs.add(record);
        }

        @Override
        public void flush() {
        }

        @Override
        public void close() throws SecurityException {
        }
    });
    bis.close();

    assertEquals(1, logs.size());
    Throwable thrown = logs.get(0).getThrown();
    assertEquals("thrown is annotated", "annotation message", thrown.getCause().getMessage());
    String message = Installer.createMessage(thrown);
    assertEquals("annontation should be ignored", "NullPointerException: root", message);
}
 
Example 10
Source File: NbServletsInterceptor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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);
}

   }
 
Example 11
Source File: NbObjectInputStream.java    From netbeans with Apache License 2.0 5 votes vote down vote up
protected Class resolveClass(ObjectStreamClass v) throws IOException, ClassNotFoundException {
    ClassLoader cl = getNBClassLoader();

    try {
        return Class.forName(v.getName(), false, cl);
    } catch (ClassNotFoundException cnfe) {
        String msg = "Offending classloader: " + cl; // NOI18N
        Exceptions.attachMessage(cnfe, msg);
        throw cnfe;
    }
}
 
Example 12
Source File: TopLoggingTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testLoggingAnnotateException() throws Exception {
    Exception e = new Exception("One");
    Exceptions.attachMessage(e, "Two");

    Logger.getLogger(TopLoggingTest.class.getName()).log(Level.INFO, "Three", e);

    String disk = readLog(true);
    if (!disk.contains("One") || !disk.contains("Two") || !disk.contains("Three")) {
        fail("There shall be One, Two, Three text in the log:\n" + disk);
    }
}
 
Example 13
Source File: LexUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static TokenSequence<GroovyTokenId> getPositionedSequence(BaseDocument doc, int offset, boolean lookBack) {
    TokenSequence<GroovyTokenId> ts = getGroovyTokenSequence(doc, offset);

    if (ts != null) {
        try {
            ts.move(offset);
        } catch (AssertionError e) {
            DataObject dobj = (DataObject) doc.getProperty(Document.StreamDescriptionProperty);

            if (dobj != null) {
                Exceptions.attachMessage(e, FileUtil.getFileDisplayName(dobj.getPrimaryFile()));
            }

            throw e;
        }

        if (!lookBack && !ts.moveNext()) {
            return null;
        } else if (lookBack && !ts.moveNext() && !ts.movePrevious()) {
            return null;
        }

        return ts;
    }

    return null;
}
 
Example 14
Source File: XMLSettingsSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
protected Class resolveClass(ObjectStreamClass v) throws IOException, ClassNotFoundException {
    ClassLoader cl = getNBClassLoader();
    try {
        return Class.forName(v.getName(), false, cl);
    } catch (ClassNotFoundException cnfe) {
        String msg = "Offending classloader: " + cl; // NOI18N
        Exceptions.attachMessage(cnfe, msg);
        throw cnfe;
    }
}
 
Example 15
Source File: PropertiesReader.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * natural ordering of the items in the collection!
 */
public static Collection<Pair<String, String>> parseBundle(String name) {
    ClassLoader loader = getLoader();
    String sname = name.replace('.', '/');
    Properties p = new Properties();
    String res = sname + ".properties";

    // #49961: don't use getResourceAsStream; catch all errors opening it
    URL u = loader != null ? loader.getResource(res) : ClassLoader.getSystemResource(res);

    if (u != null) {
        //System.err.println("Loading " + res);
        try {
            try (InputStream is = u.openStream()) {
                Collection<Pair<String, String>> col = new ArrayList<>();
                load(is, col);
                return col;
            }
        } catch (IOException e) {
            Exceptions.attachMessage(e, "While loading: " + res); // NOI18N

            return null;
        }
    }

    return null;


}
 
Example 16
Source File: LexUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static Token<GroovyTokenId> getToken(BaseDocument doc, int offset) {
    TokenSequence<GroovyTokenId> ts = getGroovyTokenSequence(doc, offset);

    if (ts != null) {
        try {
            ts.move(offset);
        } catch (AssertionError e) {
            DataObject dobj = (DataObject) doc.getProperty(Document.StreamDescriptionProperty);

            if (dobj != null) {
                Exceptions.attachMessage(e, FileUtil.getFileDisplayName(dobj.getPrimaryFile()));
            }

            throw e;
        }

        if (!ts.moveNext() && !ts.movePrevious()) {
            return null;
        }

        Token<GroovyTokenId> token = ts.token();

        return token;
    }

    return null;
}
 
Example 17
Source File: ModuleSystem.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Creates bootstrap (fixed) modules for the given manifests.
 * 
 * @param e manifest URLs.
 * @param checkedManifests manifests already processed earlier
 * @param ignoredJars JARs which should be ignored
 * @param loader module classloader for the created modules
 * 
 * @throws IOException
 * @throws DuplicateException 
 */
private void createBootModules(Enumeration<URL> e, Set<URL> checkedManifests, Set<File> ignoredJars, ClassLoader loader) throws IOException, DuplicateException {
    while (e.hasMoreElements()) {
        URL manifestUrl = e.nextElement();
        if (!checkedManifests.add(manifestUrl)) {
            // Already seen, ignore.
            continue;
        }
        URL jarURL = FileUtil.getArchiveFile(manifestUrl);
        if (jarURL != null && jarURL.getProtocol().equals("file") &&
                /* #121777 */ jarURL.getPath().startsWith("/")) {
            LOG.log(Level.FINE, "Considering JAR: {0}", jarURL);
            try {
                if (ignoredJars.contains(BaseUtilities.toFile(jarURL.toURI()))) {
                    LOG.log(Level.FINE, "ignoring JDK/JRE manifest: {0}", manifestUrl);
                    continue;
                }
            } catch (URISyntaxException x) {
                Exceptions.printStackTrace(x);
            }
        }
        LOG.log(Level.FINE, "Checking boot manifest: {0}", manifestUrl);
        
        InputStream is;
        try {
            is = manifestUrl.openStream();
        } catch (IOException ioe) {
            // Debugging for e.g. #32493 - which JAR was guilty?
            throw Exceptions.attachMessage(ioe, "URL: " + manifestUrl); // NOI18N
        }
        try {
            Manifest mani = new Manifest(is);
            Attributes attr = mani.getMainAttributes();
            if (attr.getValue("OpenIDE-Module") == null) { // NOI18N
                // Not a module.
                continue;
            }
            bootModules.add(mgr.createFixed(mani, manifestUrl, loader));
        } finally {
            is.close();
        }
    }
}
 
Example 18
Source File: XMLSettingsSupport.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/** Create an instance.
 * @return the instance of type {@link #instanceClass}
 * @exception IOException if an I/O error occured
 * @exception ClassNotFoundException if a class was not found
 */
public Object instanceCreate() throws java.io.IOException, ClassNotFoundException {
    Object inst = null;
    
    // deserialize
    inst = readSerial(getSerializedInstance());

    // default instance
    if (inst == null) {
        if (instanceMethod != null) {
            inst = createFromMethod(instanceClass, instanceMethod);
        } else {
            // use default constructor
            Class<?> clazz = instanceClass();
            if (SharedClassObject.class.isAssignableFrom(clazz)) {
                inst = SharedClassObject.findObject(clazz.asSubclass(SharedClassObject.class), false);
                if (null != inst) {
                    // instance already exists -> reset it to defaults
                    try {
                        Method method = SharedClassObject.class.getDeclaredMethod("reset", new Class[0]); // NOI18N
                        method.setAccessible(true);
                        method.invoke(inst, new Object[0]);
                    } catch (Exception e) {
                        Exceptions.printStackTrace(e);
                    }
                } else {
                    inst = SharedClassObject.findObject(clazz.asSubclass(SharedClassObject.class), true);
                }
            } else {
                try {
                    inst = newInstance(clazz);
                } catch (Exception ex) {
                    IOException ioe = new IOException();
                    ioe.initCause(ex);
                    Exceptions.attachMessage(ioe,
                                                      "Content: \n" +
                                                      getFileContent(source)); // NOI18N
                    Exceptions.attachMessage(ioe,
                                                      "Class: " + clazz); // NOI18N
                    Exceptions.attachMessage(ioe,
                                                      "Source: " +
                                                      source); // NOI18N
                    throw ioe;
                }
            }
        }
    }
    
    return inst;
}
 
Example 19
Source File: FolderObj.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public final FileObject createDataImpl(final String name, final String ext) throws java.io.IOException {
    if (name.indexOf('\\') != -1 || name.indexOf('/') != -1) {//NOI18N
        throw new IOException("Requested name contains invalid characters: " + name); // NOI18N
    }
    
    final ChildrenCache childrenCache = getChildrenCache();        
    final Mutex.Privileged mutexPrivileged = childrenCache.getMutexPrivileged();
    
    ProvidedExtensions extensions =  getProvidedExtensions();
    File file2Create;
    file2Create = BaseFileObj.getFile(getFileName().getFile(), name, ext);
    extensions.beforeCreate(this, file2Create.getName(), false);
    mutexPrivileged.enterWriteAccess();

    FileObj retVal;
    FileNaming childName;
    try {
        Watcher.lock(this);
        createData(file2Create);
        childName = getChildrenCache().getChild(file2Create.getName(), true);
        if (childName != null && childName.isDirectory()) {
            childName = NamingFactory.fromFile(getFileName(), file2Create, true);
        }
        if (childName != null) {
            childName = NamingFactory.checkCaseSensitivity(childName, file2Create);
        }

    } finally {
        mutexPrivileged.exitWriteAccess();
    }

    final FileObjectFactory factory = getFactory();
    retVal = null;
    if (factory != null) {
        final BaseFileObj fo = factory.getValidFileObject(file2Create, FileObjectFactory.Caller.Others);
        try {
            retVal = (FileObj) fo;
        } catch (ClassCastException ex) {
            boolean dir = file2Create.isDirectory();
            boolean file = file2Create.isFile();
            Exceptions.attachMessage(ex, "isDir: " + dir); // NOI18N
            Exceptions.attachMessage(ex, "isFile: " + file); // NOI18N
            Exceptions.attachMessage(ex, "file: " + file2Create); // NOI18N
            Exceptions.attachMessage(ex, "fo: " + fo); // NOI18N
            Exceptions.attachMessage(ex, "fn: " + Integer.toHexString(System.identityHashCode(childName))); // NOI18N
            Exceptions.attachMessage(ex, "dump: " + NamingFactory.dumpId(childName.getId())); // NOI18N
            throw ex;
        }
    }

    if (retVal != null) {            
        if (retVal instanceof FileObj) {
            retVal.setLastModified(file2Create.lastModified(), file2Create, false);
        }
        retVal.fireFileDataCreatedEvent(false);
    } else {
        FSException.io("EXC_CannotCreateData", file2Create.getName(), getPath());// NOI18N
    }
    getProvidedExtensions().createSuccess(retVal);
    return retVal;
}
 
Example 20
Source File: InvocationExceptionTranslated.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public synchronized String getMessage() {
    if (message == null) {
        try {
            Method getMessageMethod = ClassTypeWrapper.concreteMethodByName((ClassType) ValueWrapper.type(exeption),
                        "getMessage", "()Ljava/lang/String;");  // NOI18N
            if (getMessageMethod == null) {
                if (invocationMessage != null) {
                    message = "";
                } else {
                    message = "Unknown exception message";
                }
            } else {
                try {
                    StringReference sr = (StringReference) debugger.invokeMethod (
                            preferredThread,
                            exeption,
                            getMessageMethod,
                            new Value [0],
                            this
                        );
                    message = sr != null ? StringReferenceWrapper.value(sr) : ""; // NOI18N
                } catch (InvalidExpressionException ex) {
                    if (ex.getTargetException() == this) {
                        String msg = getMessageFromField();
                        if (msg == null) {
                            if (invocationMessage != null) {
                                message = "";
                            } else {
                                message = "Unknown exception message";
                            }
                        }
                    } else {
                        return ex.getMessage();
                    }
                } catch (VMMismatchException vmMismatchEx) {
                    VirtualMachine ptvm = ((preferredThread != null) ? preferredThread.getThreadReference().virtualMachine() : null);
                    VirtualMachine ctvm = null;
                    JPDAThread currentThread = debugger.getCurrentThread();
                    if (currentThread != null) {
                        ctvm = ((JPDAThreadImpl) currentThread).getThreadReference().virtualMachine();
                    }
                    throw Exceptions.attachMessage(vmMismatchEx, "DBG VM = "+printVM(debugger.getVirtualMachine())+
                                                               ", preferredThread VM = "+printVM(ptvm)+
                                                               ", currentThread VM = "+printVM(ctvm)+
                                                               ", exeption VM = "+printVM(exeption.virtualMachine()));
                }
            }
        } catch (InternalExceptionWrapper iex) {
            return iex.getMessage();
        } catch (VMDisconnectedExceptionWrapper vdex) {
            return vdex.getMessage();
        } catch (ObjectCollectedExceptionWrapper ocex) {
            Exceptions.printStackTrace(ocex);
            return ocex.getMessage();
        } catch (ClassNotPreparedExceptionWrapper cnpex) {
            return cnpex.getMessage();
        }
    }
    if (invocationMessage != null) {
        return invocationMessage + ": " + message;
    } else {
        return message;
    }
}