Java Code Examples for org.openide.util.Exceptions

The following are top voted examples for showing how to use org.openide.util.Exceptions. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: incubator-netbeans   File: BIEditorSupport.java   Source Code and License 6 votes vote down vote up
/** This is called by the multiview elements whenever they are created
 * (and given a observer knowing their multiview TopComponent). It is
 * important during deserialization and clonig the multiview - i.e. during
 * the operations we have no control over. But anytime a multiview is
 * created, this method gets called.
 */
private void setTopComponent(TopComponent topComp) {
    multiviewTC = (CloneableTopComponent)topComp;
    updateMVTCName();

    if (topComponentsListener == null) {
        topComponentsListener = new TopComponentsListener();
        TopComponent.getRegistry().addPropertyChangeListener(topComponentsListener);
    }
    opened.add(this);
    try {
        addStatusListener(getDataObject().getPrimaryFile().getFileSystem());
    } catch (FileStateInvalidException fsiex) {
        Exceptions.printStackTrace(fsiex);
    }

}
 
Example 2
Project: incubator-netbeans   File: JavadocGenerator.java   Source Code and License 6 votes vote down vote up
/**
 * Updates settings used by this generator. It should be called outside locks.
 * @param file a file where the generated content will be added
 */
public void updateSettings(FileObject file) {
    DataObject dobj = null;
    DataFolder folder = null;
    try {
        dobj = DataObject.find(file);
        folder = dobj.getFolder();
    } catch (DataObjectNotFoundException ex) {
        Exceptions.printStackTrace(ex);
    }
    if (dobj == null || folder == null) {
        return;
    }
    for (CreateFromTemplateAttributesProvider provider
            : Lookup.getDefault().lookupAll(CreateFromTemplateAttributesProvider.class)) {
        Map<String, ?> attrs = provider.attributesFor(dobj, folder, "XXX"); // NOI18N
        if (attrs == null) {
            continue;
        }
        Object aName = attrs.get("user"); // NOI18N
        if (aName != null) {
            author = aName.toString();
            break;
        }
    }
}
 
Example 3
Project: incubator-netbeans   File: FileNameController.java   Source Code and License 6 votes vote down vote up
private void hideInfo() {
    watcherLogger.finer("hideInfo()");                          //NOI18N

    txtComp.setEnabled(true);
    try {
        ignoreFileNamePatternChanges = true;
        if (doc.getText(0, doc.getLength()).equals(getInfoText())) {
            doc.remove(0, doc.getLength());
        }
    } catch (BadLocationException ex) {
        Exceptions.printStackTrace(ex);
    } finally {
        ignoreFileNamePatternChanges = false;
        txtComp.setForeground(foregroundColor);
        infoDisplayed = false;
    }
}
 
Example 4
Project: incubator-netbeans   File: TextDetailTest.java   Source Code and License 6 votes vote down vote up
private TextDetail createMockTextDetail(String line, String match) {
    FileSystem fs = FileUtil.createMemoryFileSystem();
    try {
        FileObject fo = fs.getRoot().createData("mockMatch.txt");
        SearchPattern sp = SearchPattern.create(match, false, false, false);
        DataObject dob = DataObject.find(fo);
        TextDetail td = new TextDetail(dob, sp);
        td.setLine(1);
        int col0 = line.indexOf(match) + 1;
        td.setColumn(col0);
        td.setMatchedText(match);
        td.setMarkLength(match.length());
        td.setStartOffset(col0);
        td.setEndOffset(col0 + match.length());
        td.setLineText(line);
        return td;
    } catch (Exception e) {
        Exceptions.printStackTrace(e);
        return null;
    }
}
 
Example 5
Project: incubator-netbeans   File: FormEditor.java   Source Code and License 6 votes vote down vote up
public boolean loadForm() {
    if (!formLoaded) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                loadFormData();
            }
        };
        if (java.awt.EventQueue.isDispatchThread()) {
            r.run();
        } else { // loading must be done in AWT event dispatch thread
            try {
                java.awt.EventQueue.invokeAndWait(r);
            } catch (Exception ex) {
                Exceptions.printStackTrace(ex);
            }
        }
    }
    return formLoaded;
}
 
Example 6
Project: incubator-netbeans   File: CoverageManagerImpl.java   Source Code and License 6 votes vote down vote up
void focused(FileObject fo, JTextComponent target) {
    Project project = FileOwnerQuery.getOwner(fo);
    if (project != null) {
        CoverageProvider provider = getProvider(project);
        if (provider != null && provider.isEnabled()) {
            try {
                EditorCookie ec = DataLoadersBridge.getDefault().getCookie(fo, EditorCookie.class);
                if (ec != null) {
                    Document doc = ec.getDocument();
                    if (doc == null) {
                        return;
                    }

                    doc.putProperty(COVERAGE_DOC_PROPERTY, null);
                    CoverageHighlightsContainer container = CoverageHighlightsLayerFactory.getContainer(target);
                    if (container != null) {
                        container.refresh();
                    }
                }
            } catch (IOException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
    }
}
 
Example 7
Project: incubator-netbeans   File: JShellEnvironment.java   Source Code and License 6 votes vote down vote up
private void postCloseCleanup() {
    try {
        // try to close the dataobject
        DataObject d = DataObject.find(getConsoleFile());
        EditorCookie cake = d.getLookup().lookup(EditorCookie.class);
        cake.close();
        // discard the dataobject
        synchronized (this) {
            if (document == null) {
                return;
            }
            document = null;
        }
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    }
    if (controlsIO) {
        inputOutput.closeInputOutput();
    }
    ShellRegistry.get().closed(this);
}
 
Example 8
Project: incubator-netbeans   File: XMLSettingsSupport.java   Source Code and License 6 votes vote down vote up
/** reade codenamebase + revision */
private void resolveModuleElm (String codeName) {
    if (codeName != null) {
        int slash = codeName.indexOf ("/"); // NOI18N
        if (slash == -1) {
            codeNameBase = codeName;
            codeNameRelease = -1;
        } else {
            codeNameBase = codeName.substring (0, slash);
            try {
                codeNameRelease = Integer.parseInt(codeName.substring(slash + 1));
            } catch (NumberFormatException ex) {
                Exceptions.attachLocalizedMessage(ex,
                                                  "Content: \n" +
                                                  getFileContent(source)); // NOI18N
                Exceptions.attachLocalizedMessage(ex,
                                                  "Source: " + source); // NOI18N
                Logger.getLogger(XMLSettingsSupport.class.getName()).log(Level.WARNING, null, ex);
                codeNameRelease = -1;
            }
        }
    } else {
        codeNameBase = null;
        codeNameRelease = -1;
    }
}
 
Example 9
Project: incubator-netbeans   File: BinaryAnalyserTest.java   Source Code and License 6 votes vote down vote up
@CheckForNull
private static URL findRtJar() {
    final String boot = System.getProperty("sun.boot.class.path");  //NOI18N
    if (boot != null) {
        for (String part : boot.split(File.pathSeparator)) {
            if (part.contains("rt.jar")) {  //NOI18N
                final File rtJar = FileUtil.normalizeFile(new File(part));
                try {
                    return FileUtil.getArchiveRoot(BaseUtilities.toURI(rtJar).toURL());
                } catch (MalformedURLException e) {
                    Exceptions.printStackTrace(e);
                }
            }
        }
    }
    return null;
}
 
Example 10
Project: incubator-netbeans   File: SyncDocumentRegion.java   Source Code and License 6 votes vote down vote up
/**
 * Propagate text of the first region into all other regions.
 */
public void sync() {
    String firstRegionText = getFirstRegionText();
    if (firstRegionText != null) {
        int regionCount = getRegionCount();
        for (int i = 1; i < regionCount; i++) {
            MutablePositionRegion region = getRegion(i);
            int offset = region.getStartOffset();
            int length = region.getEndOffset() - offset;
            try {
                if (!CharSequenceUtilities.textEquals(firstRegionText, DocumentUtilities.getText(doc, offset, length))) {
                    if (firstRegionText.length() > 0) {
                        doc.insertString(offset, firstRegionText, null);
                    }
                    doc.remove(offset + firstRegionText.length(), length);
                }
            } catch (BadLocationException e) {
                Exceptions.printStackTrace(e);
            }

        }
    }
}
 
Example 11
Project: incubator-netbeans   File: ClassMemberPanelUI.java   Source Code and License 6 votes vote down vote up
private ElementJavadoc getJavaDocFor(
        @NonNull final ElementNode node,
        @NullAllowed final Callable<Boolean> cancel) {
    ElementNode root = getRootNode();
    if ( root == null ) {
        return null;
    }
    final ElementHandle<? extends Element> eh = node.getDescritption().getElementHandle();
    if (eh == null) {
        return null;
    }
    final JavaSource js = JavaSource.forFileObject( root.getDescritption().fileObject );
    if (js == null) {
        return null;
    }
    final JavaDocCalculator calculator = new JavaDocCalculator(eh, cancel);
    try {
        js.runUserActionTask( calculator, true );
    } catch( IOException ioE ) {
        Exceptions.printStackTrace( ioE );
        return null;
    }
    return calculator.doc;
}
 
Example 12
Project: incubator-netbeans   File: JShellConnection.java   Source Code and License 6 votes vote down vote up
/**
 * Shuts down the connection, may be called for local or remote close.
 */
void shutDown() {
    try {
        LOG.log(Level.FINE, "notifyShutdown: closing control socket: {0}", controlSocket);
        if (controlSocket != null) {
            // assumes both input and output terminate
            controlSocket.close();
        }
        ostm.close();
        istm.close();
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    } finally {
        synchronized (this) {
            closed = true;
            notify();
        }
    }
}
 
Example 13
Project: incubator-netbeans   File: GenerateJavadocAction.java   Source Code and License 6 votes vote down vote up
private void generate(final Document doc, final Descriptor desc, final JTextComponent jtc) throws BadLocationException {
    final Indent ie = Indent.get(doc);
    try {
        ie.lock();
        NbDocument.runAtomicAsUser((StyledDocument) doc, new Runnable() {

            public void run() {
                try {
                    int caretPos = jtc.getCaretPosition();
                    generateJavadoc(doc, desc, ie);
                    // move caret
                    jtc.setCaretPosition(caretPos);
                } catch (BadLocationException ex) {
                    Exceptions.printStackTrace(ex);
                }
            }

        });
    } finally {
        ie.unlock();
    }
}
 
Example 14
Project: incubator-netbeans   File: BeanAliasTypeDescriptor.java   Source Code and License 6 votes vote down vote up
@Override
public void open() {
    FileObject fo = getFileObject();
    SpringConfigModel model = SpringConfigModel.forFileObject(fo);
    if (model == null) {
        return;
    }
    try {
        model.runReadAction(new Action<SpringBeans>() {

            public void run(SpringBeans beans) {
                SpringBean bean = beans.findBean(getSimpleName());
                if (bean == null) {
                    return;
                }

                SpringBeansUIs.createGoToBeanAction(bean).invoke();
            }
        });
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    }
}
 
Example 15
Project: incubator-netbeans   File: VisualDebuggerListener.java   Source Code and License 6 votes vote down vote up
private void stopDebuggerRemoteService(JPDADebugger d) {
    ClassObjectReference serviceClass = RemoteServices.getServiceClass(d, RemoteServices.ServiceType.AWT);
    if (serviceClass == null) {
        return ;
    }
    try {
        ReferenceType serviceType = serviceClass.reflectedType();
        Field awtAccessLoop = serviceType.fieldByName("awtAccessLoop"); // NOI18N
        if (awtAccessLoop != null) {
            ((ClassType) serviceType).setValue(awtAccessLoop, serviceClass.virtualMachine().mirrorOf(false));
        }
        serviceClass.enableCollection();
    } catch (VMDisconnectedException vdex) {
        // Ignore
    } catch (Exception ex) {
        Exceptions.printStackTrace(ex);
    }
}
 
Example 16
Project: incubator-netbeans   File: HintsPanel.java   Source Code and License 6 votes vote down vote up
private void newButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newButtonActionPerformed
        try {
            FileObject tempFO = FileUtil.getConfigFile(DECLARATIVE_HINT_TEMPLATE_LOCATION); // NOI18N
            FileObject folderFO = FileUtil.getConfigFile("rules");
            if (folderFO == null) {
                folderFO = FileUtil.getConfigRoot().createFolder("rules");
            }
            DataFolder folder = (DataFolder) DataObject.find(folderFO);
            DataObject template = DataObject.find(tempFO);
            DataObject newIfcDO = template.createFromTemplate(folder, null);
            RulesManager.getInstance().reload();
            cpBased.reset();
            errorTreeModel = constructTM(Utilities.getBatchSupportedHints(cpBased).keySet(), false);
            setModel(errorTreeModel);
            logic.errorTreeModel = errorTreeModel;
            HintMetadata newHint = getHintByName(newIfcDO.getPrimaryFile().getNameExt());
            logic.writableSettings.setEnabled(newHint, true);
            select(newHint);
            hasNewHints = true;
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        }
}
 
Example 17
Project: incubator-netbeans   File: DefaultClassPathProvider.java   Source Code and License 6 votes vote down vote up
private void fire() {
    LOG.log(Level.FINEST, "Request to fire an event");      //NOI18N
    synchronized (this) {
        if (task == null) {
            LOG.log(Level.FINEST, "Scheduled firer task");  //NOI18N
            final Future<Project[]> becomeProjects = OpenProjects.getDefault().openProjects();
            task = RP.create(new Runnable() {
                @Override
                public void run() {
                    try {
                        becomeProjects.get();
                        support.firePropertyChange(PROP_RESOURCES,null,null);
                        LOG.log(Level.FINEST, "Fired an event");    //NOI18N
                    } catch (InterruptedException | ExecutionException ex) {
                        Exceptions.printStackTrace(ex);
                    } finally {
                        task = null;    //Write barrier
                    }
                }
            });
            task.schedule(0);
        }
    }
}
 
Example 18
Project: incubator-netbeans   File: Saas.java   Source Code and License 6 votes vote down vote up
public void save() {
    try {
        SaasUtil.saveSaas(this, getSaasFile());
        if (getProperties().size() > 0) {
            java.io.OutputStream out = null;
            try {
                out = getPropFile(true).getOutputStream();
                getProperties().store(out, getDisplayName() + " : " + getUrl());
            } finally {
                if (out != null) {
                    out.close();
                }
            }
        }
    } catch (Exception e) {
        Exceptions.printStackTrace(e);
    }
}
 
Example 19
Project: Pogamut3   File: ExplorerFactory.java   Source Code and License 6 votes vote down vote up
@Override
public void openEditor(PrimitiveData metadata) {
    String javaFilePath = metadata.classFQN.replace('.', '/') + ".java";
    for (FileObject curRoot : GlobalPathRegistry.getDefault().getSourceRoots()) {
        FileObject fileObject = curRoot.getFileObject(javaFilePath);
        if (fileObject != null) {
            DataObject dobj = null;
            try {
                dobj = DataObject.find(fileObject);
            } catch (DataObjectNotFoundException ex) {
                Exceptions.printStackTrace(ex);
            }
            if (dobj != null) {
                EditorCookie ec = (EditorCookie) dobj.getCookie(EditorCookie.class);
                if (ec != null) {
                    ec.open();
                }
            }
        }
    }
}
 
Example 20
Project: Proyecto-DASI   File: ControladorVisualizacionSimulRosace.java   Source Code and License 6 votes vote down vote up
public boolean verificarCaracteristicasEscenarioSeleccionado ( File ficheroSeleccionado,String orgModelo,int numRobots ){
        try {
            escenarioSimulComp = itfPersistenciaSimul.obtenerInfoEscenarioSimulacion(ficheroSeleccionado.getName());
        } catch (Exception ex) {
            Exceptions.printStackTrace(ex);
        }
       if(escenarioSimulComp == null ) return false;
    identEquipoActual=escenarioSimulComp.getIdentEscenario();
       numeroRobots = escenarioSimulComp.getNumRobots();
       modeloOrganizativo= escenarioSimulComp.getmodeloOrganizativo();
      if(this.numeroRobots==numRobots &&this.modeloOrganizativo.equalsIgnoreCase(orgModelo)){
          // se envia notificacion al agente controlador con el computacional obtenido
       escenarioSimulComp.setGestorEscenarios(gestionEscComp);  
       escenarioValidoObtenido = true;
       return true;
      }else {
          visorControlSim.visualizarConsejo("Fichero seleccionado No valido ", "El modelo organizativo del fichero seleccionado: "+orgModelo
           + " o el  numero de Robots = : "+ numRobots + " No coinciden ", "Seleccione otro fichero o  cree uno nuevo ");
          return false;
       }
}
 
Example 21
Project: incubator-netbeans   File: EntityManagerGenerationStrategyResolverFactory.java   Source Code and License 6 votes vote down vote up
private PersistenceUnit getPersistenceUnit(FileObject target) {
    PersistenceScope persistenceScope = PersistenceScope.getPersistenceScope(target);
    if (persistenceScope == null) {
        return null;
    }

    try {
        // TODO: fix ASAP! 1st PU is taken, needs to find the one which realy owns given file
        Persistence persistence = PersistenceMetadata.getDefault().getRoot(persistenceScope.getPersistenceXml());
        if (persistence != null) {
            return persistence.getPersistenceUnit(0);
        }
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    }
    return null;
}
 
Example 22
Project: incubator-netbeans   File: YamlCompletion.java   Source Code and License 6 votes vote down vote up
@Override
public String getPrefix(ParserResult info, int caretOffset, boolean upToOffset) {
    if (caretOffset > 0) {
        try {
            Document doc = ((YamlParserResult) info).getSnapshot().getSource().getDocument(false);
            if (doc != null) {
                return doc.getText(caretOffset - 1, 1);
            } else {
                return null;
            }
        } catch (BadLocationException ex) {
            Exceptions.printStackTrace(ex);
        }
    }

    return null;
}
 
Example 23
Project: incubator-netbeans   File: ModelProperty.java   Source Code and License 6 votes vote down vote up
public PropertyEditor getPropertyEditor() {
    if (mdl.getPropertyEditorClass() != null) {
        try {
            //System.err.println("ModelProperty creating a " 
            //+ mdl.getPropertyEditorClass());
            Constructor c = mdl.getPropertyEditorClass().getConstructor();
            c.setAccessible(true);

            return (PropertyEditor) c.newInstance(new Object[0]);
        } catch (Exception e) {
            Exceptions.printStackTrace(e);

            return new PropUtils.NoPropertyEditorEditor();
        }
    }

    return super.getPropertyEditor();
}
 
Example 24
Project: incubator-netbeans   File: EntityClosure.java   Source Code and License 6 votes vote down vote up
private void redoClosure() {
    Set<String> allEntities = new HashSet<String>(availableEntities);
    allEntities.addAll(selectedEntities);
    
    referencedEntities.clear();
    try{
        referencedEntities.addAll(getReferencedEntitiesTransitively(wantedEntities));
    }catch (IOException ioe){
        Exceptions.printStackTrace(ioe);
    }
    
    
    selectedEntities.clear();
    selectedEntities.addAll(wantedEntities);
    selectedEntities.addAll(referencedEntities);
    
    availableEntities.clear();
    availableEntities.addAll(allEntities);
    availableEntities.removeAll(selectedEntities);
}
 
Example 25
Project: incubator-netbeans   File: EditorContextBridge.java   Source Code and License 6 votes vote down vote up
private static String getReflectionMethodValue(String methodName) {
    try {
        return (String) getContext().getClass().getMethod(methodName).invoke(getContext());
    } catch (java.lang.reflect.InvocationTargetException itex) {
        Throwable tex = itex.getTargetException();
        if (tex instanceof RuntimeException) {
            throw (RuntimeException) tex;
        } else {
            ErrorManager.getDefault().notify(tex);
            return null;
        }
    } catch (Exception ex) {
        Exceptions.printStackTrace(ex);
        return null;
    }
}
 
Example 26
Project: incubator-netbeans   File: AbstractNode.java   Source Code and License 6 votes vote down vote up
/** Checks whether subclass overrides a method
 */
private boolean overridesAMethod(String name, Class[] arguments) {
    // we are subclass of AbstractNode
    try {
        java.lang.reflect.Method m = getClass().getMethod(name, arguments);

        if (m.getDeclaringClass() != AbstractNode.class) {
            // ok somebody overriden the method
            return true;
        }
    } catch (NoSuchMethodException ex) {
        Exceptions.printStackTrace(ex);
    }

    return false;
}
 
Example 27
Project: incubator-netbeans   File: FolderChildrenTest.java   Source Code and License 6 votes vote down vote up
@Override
public String[] children(String f) {
    if ("".equals(f)) {
        return new String[] {"content"};
    } else if ("content".equals(f)) {
        try {
            if (contentSemaphore.tryAcquire(1, 10, TimeUnit.SECONDS)) {
                return new String[] {"a.txt", "b.txt", "c.txt"};
            } else {
                return new String[0];
            }
        } catch (InterruptedException ex) {
            Exceptions.printStackTrace(ex);
            return new String[0];
        }
    } else {
        return new String[0];
    }
}
 
Example 28
Project: incubator-netbeans   File: FindLocalUsagesQuery.java   Source Code and License 6 votes vote down vote up
@Override
public Void visitMemberSelect(MemberSelectTree node, Void p) {
    Element el = info.getTrees().getElement(getCurrentPath());
    if (toFind.equals(el)) {
        try {
            int[] span = treeUtils.findNameSpan(node);
            if(span != null) {
                MutablePositionRegion region = createRegion(doc, span[0], span[1]);
                usages.add(region);
            }
        } catch (BadLocationException ex) {
            Exceptions.printStackTrace(ex);
        }
    }
    return super.visitMemberSelect(node, p);
}
 
Example 29
Project: incubator-netbeans   File: HtmlIndex.java   Source Code and License 6 votes vote down vote up
/**
 *
 * @param keyName
 * @param value
 * @return returns a collection of files which contains the keyName key and the
 * value matches the value regular expression
 */
public Collection<FileObject> find(String keyName, String value) {
    try {
        String searchExpression = ".*(" + value + ")[,;].*"; //NOI18N
        Collection<FileObject> matchedFiles = new LinkedList<>();
        Collection<? extends IndexResult> results = querySupport.query(keyName, searchExpression, QuerySupport.Kind.REGEXP, keyName);
        for (IndexResult result : filterDeletedFiles(results)) {
            matchedFiles.add(result.getFile());
        }
        return matchedFiles;
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    }

    return Collections.emptyList();
}
 
Example 30
Project: incubator-netbeans   File: NativeExecutionBaseTestCase.java   Source Code and License 6 votes vote down vote up
protected synchronized  String getRemoteTmpDir() {
    if (remoteTmpDir == null) {
        final ExecutionEnvironment local = ExecutionEnvironmentFactory.getLocal();
        MacroExpander expander = MacroExpanderFactory.getExpander(local);
        String id;
        try {
            id = expander.expandPredefinedMacros("${hostname}-${osname}-${platform}${_isa}"); // NOI18N
        } catch (ParseException ex) {
            id = local.getHost();
            Exceptions.printStackTrace(ex);
        }
        remoteTmpDir = "/tmp/" + id + "-" + System.getProperty("user.name") + "-" + getTestExecutionEnvironment().getUser();
        if (POSTFIX != null) {
            remoteTmpDir += '-' + POSTFIX;
        }
    }
    return remoteTmpDir;
}
 
Example 31
Project: incubator-netbeans   File: JavaVariablesFilter.java   Source Code and License 5 votes vote down vote up
private static boolean isInstanceOf(JPDAClassType ct, String className) {
    if (ct == null) return false;
    try {
        java.lang.reflect.Method isInstanceOfMethod = ct.getClass().getMethod("isInstanceOf", String.class);
        return (Boolean) isInstanceOfMethod.invoke(ct, className);
    } catch (Exception ex) {
        Exceptions.printStackTrace(ex);
        return false;
    }
}
 
Example 32
Project: incubator-netbeans   File: DocumentNode.java   Source Code and License 5 votes vote down vote up
private void refreshKeys() {
    try {
        if (first_run) {
            //postpone the initialization until scanning finishes as we need to wait for some data
            //to be properly initialized. If CssIndex.create() is called to soon during
            //the startup then it won't obtain proper source roots
            first_run = false;
            ParserManager.parseWhenScanFinished("text/css", refreshKeysTask); //NOI18N
        } else {
            ParserManager.parse("text/css", refreshKeysTask); //NOI18N
        }
    } catch (ParseException ex) {
        Exceptions.printStackTrace(ex);
    }
}
 
Example 33
Project: incubator-netbeans   File: DocumentCannotBeClosedWhenReadLockedTest.java   Source Code and License 5 votes vote down vote up
public void unmarkModified() {
    unmarkModifiedStarted.countDown();
    try {
        Thread.sleep(500);
    } catch (InterruptedException ex) {
        Exceptions.printStackTrace(ex);
    }
    modified = false;
    unmarkModifiedFinished.countDown();
}
 
Example 34
Project: incubator-netbeans   File: AptSourceFileManager.java   Source Code and License 5 votes vote down vote up
private URL getOwnerRoot (final javax.tools.FileObject sibling) {
    try {
        return siblings.hasSibling() ? getOwnerRootSib(siblings.getSibling()) :
            (sibling == null ? getOwnerRootNoSib() : getOwnerRootSib(sibling.toUri().toURL()));
    } catch (MalformedURLException ex) {
        Exceptions.printStackTrace(ex);
        return null;
    }
}
 
Example 35
Project: incubator-netbeans   File: MethodCandidateChooser.java   Source Code and License 5 votes vote down vote up
private void openSelected() {
    PopupUtil.hidePopup();
    
    Candidate cand = (Candidate) jList1.getSelectedValue();
    
    if (cand != null) {
        try {
            cand.fix.implement();
        } catch (Exception ex) {
            Exceptions.printStackTrace(ex);
        }
    }
}
 
Example 36
Project: incubator-netbeans   File: CloneableEditorAssociateTest.java   Source Code and License 5 votes vote down vote up
public void markModified() throws IOException {
    if (cannotBeModified != null) {
        final String notify = cannotBeModified;
        IOException e = new IOException () {
            @Override
            public String getLocalizedMessage () {
                return notify;
            }
        };
        Exceptions.attachLocalizedMessage(e, cannotBeModified);
        throw e;
    }
    
    modified = true;
}
 
Example 37
Project: incubator-netbeans   File: ExcludeDepAction.java   Source Code and License 5 votes vote down vote up
@Override public void actionPerformed(ActionEvent e) {
    FixVersionConflictPanel.ExclusionTargets et =
            new FixVersionConflictPanel.ExclusionTargets(node, findNewest(node, true));
    Set<Artifact> exclTargets = et.getAll();

    if (!model.startTransaction()) {
        return;
    }
    try {
        excludeDepFromModel(node.getImpl(), exclTargets);
    } finally {
        try {
            model.endTransaction();
        } catch (IllegalStateException ex) {
            StatusDisplayer.getDefault().setStatusText(
                    NbBundle.getMessage(DependencyGraphScene.class, "ERR_UpdateModel", Exceptions.findLocalizedMessage(ex)), 
                    StatusDisplayer.IMPORTANCE_ERROR_HIGHLIGHT);
            return;
        }
    }

    HashSet<MavenDependencyNode> conflictParents = new HashSet<MavenDependencyNode>();
    for (Artifact artif : exclTargets) {
        conflictParents.addAll(et.getConflictParents(artif));
    }
    updateGraphAfterExclusion(node, exclTargets, conflictParents);

    save();
}
 
Example 38
Project: incubator-netbeans   File: OutWriterTest.java   Source Code and License 5 votes vote down vote up
private void delay(int millis) {
    try {
        Thread.sleep(millis);
    } catch (InterruptedException ex) {
        Exceptions.printStackTrace(ex);
    }
}
 
Example 39
Project: incubator-netbeans   File: NFABasedBulkSearch.java   Source Code and License 5 votes vote down vote up
@Override
public boolean matches(InputStream encoded, AtomicBoolean cancel, BulkPattern patternIn) {
    try {
        return !matchesImpl(encoded, cancel, patternIn, false).isEmpty();
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
        return false;
    }
}
 
Example 40
Project: incubator-netbeans   File: RenameTransaction.java   Source Code and License 5 votes vote down vote up
private void restore() {
    for (Handle handle : handles) {
        try {
            handle.restore();
        } catch (IOException e) {
            Exceptions.printStackTrace(e);
        }
    }
}
 
Example 41
Project: incubator-netbeans   File: CustomizerProviderImpl.java   Source Code and License 5 votes vote down vote up
public void run() {
    try {
        JFrame f = (JFrame) WindowManager.getDefault().getMainWindow();
        Component c = f.getGlassPane();
        c.setVisible(show);
        c.setCursor(show ? Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR) : null);
    } catch (NullPointerException npe) {
        Exceptions.printStackTrace(npe);
    }
}
 
Example 42
Project: incubator-netbeans   File: HintsControllerImpl.java   Source Code and License 5 votes vote down vote up
public static void setErrors(FileObject file, String layer, Collection<? extends ErrorDescription> errors) {
    try {
        setErrorsImpl(file, layer, errors);
    } catch (IOException e) {
        Exceptions.printStackTrace(e);
    }
}
 
Example 43
Project: incubator-netbeans   File: RsrcLoader.java   Source Code and License 5 votes vote down vote up
public void handleTemplateException(TemplateException ex, Environment env, Writer w) throws TemplateException {
    try {
        w.append(ex.getLocalizedMessage());
        LOG.log(Level.INFO, "Failure processing " + fo, ex);
        LOG.log(Level.INFO, "Bindings:"); // NOI18N
        for (Map.Entry<String, Object> entry : engineScope.entrySet()) {
            LOG.log(Level.INFO, "  key: " + entry.getKey() + " value: " + entry.getValue()); // NOI18N
        }
    } catch (IOException e) {
        Exceptions.printStackTrace(e);
    }
}
 
Example 44
Project: incubator-netbeans   File: ModuleNode.java   Source Code and License 5 votes vote down vote up
@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;
}
 
Example 45
Project: incubator-netbeans   File: ScreenshotComponent.java   Source Code and License 5 votes vote down vote up
private void selectComponent(ComponentInfo ci, boolean reActivated) {
    Node node = null;
    if (ci != null) {
        Rectangle oldSelection = null;
        if (selection != null) {
            oldSelection = selection;
        }
        selection = ci.getWindowBounds();
        if (oldSelection != null) {
            if (oldSelection.equals(selection) && !reActivated) {
                return ; // already selected
            }
            repaint((int) (scale * oldSelection.x), (int) (scale * oldSelection.y),
                    (int) (scale * oldSelection.width) + 3, (int) (scale * oldSelection.height) + 3);
        }
        repaint((int) (scale * selection.x), (int) (scale * selection.y),
                (int) (scale * selection.width) + 3, (int) (scale * selection.height) + 3);
        logger.fine("New selection = "+selection);
        node = componentNodes.findNodeFor(ci);
        logger.fine("FindNodeFor("+ci+") on '"+componentNodes+"' gives: "+node);
    }
    Node[] nodes;
    if (node != null) {
        nodes = new Node[] { node };
    } else {
        nodes = new Node[] {};
    }
    logger.fine("setActivated/SelectedNodes("+Arrays.toString(nodes)+")");
    setActivatedNodes(nodes);
    try {
        ComponentHierarchy.getInstance().getExplorerManager().setSelectedNodes(nodes);
    } catch (PropertyVetoException ex) {
        Exceptions.printStackTrace(ex);
    }
}
 
Example 46
Project: incubator-netbeans   File: SQLDataLoaderBeanInfo.java   Source Code and License 5 votes vote down vote up
public BeanInfo[] getAdditionalBeanInfo () {
    try {
        return new BeanInfo[] { Introspector.getBeanInfo(UniFileLoader.class) };
    } catch (IntrospectionException ie) {
 Exceptions.printStackTrace(ie);
        return null;
    }
}
 
Example 47
Project: incubator-netbeans   File: WebKitDebuggingTransport.java   Source Code and License 5 votes vote down vote up
@Override
public Void call(final String p) {
    RP.post(new Runnable() {
        @Override
        public void run() {
            try {
                JSONObject json = (JSONObject)JSONValue.parseWithException(p);
                responseCallback.handleResponse(new Response(json));
            } catch (ParseException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
    });
    return null;
}
 
Example 48
Project: incubator-netbeans   File: CPWhereUsedQueryPlugin.java   Source Code and License 5 votes vote down vote up
@Override
public Problem prepare(final RefactoringElementsBag elements) {
    try {
        if (cancelled) {
            return null;
        }

        Lookup lookup = refactoring.getRefactoringSource();
        RefactoringElementContext context = lookup.lookup(RefactoringElementContext.class);
        Node element = context.getElement();
        if(element != null) {
            switch (element.type()) {
                case cp_variable:
                    findVariables(context, elements);
                    break;

                case cp_mixin_name:
                    findMixins(context, elements);
                    break;
            }
        }

    } catch (IOException | ParseException ex) {
        Exceptions.printStackTrace(ex);
        String msg = ex.getLocalizedMessage();
        return new Problem(true, msg != null ? msg : ex.toString());
    }
    return null; //no problem
}
 
Example 49
Project: incubator-netbeans   File: TaskProvider.java   Source Code and License 5 votes vote down vote up
private static synchronized void updateErrorsInRoot(
        final Callback callback,
        final FileObject root,
        final AtomicBoolean cancelled) {
    Set<FileObject> filesWithErrors = getFilesWithAttachedErrors(root);
    Set<FileObject> fixedFiles = new HashSet<FileObject>(filesWithErrors);
    Set<FileObject> nueFilesWithErrors = new HashSet<FileObject>();

    try {
        for (URL u : TaskCache.getDefault().getAllFilesWithRecord(root.toURL())) {
            if (cancelled.get()) {
                return;
            }
            FileObject file = URLMapper.findFileObject(u);

            if (file != null) {
                List<Task> result = TaskCache.getDefault().getErrors(file);

                LOG.log(Level.FINE, "Setting {1} for {0}\n", new Object[] {file, result});

                callback.setTasks(file, result);

                if (!fixedFiles.remove(file)) {
                    nueFilesWithErrors.add(file);
                }
            }
        }
    } catch (IOException e) {
        Exceptions.printStackTrace(e);
    }
    
    for (FileObject f : fixedFiles) {
        LOG.log(Level.FINE, "Clearing errors for {0}", f);
        callback.setTasks(f, Collections.<Task>emptyList());
    }
    
    filesWithErrors.addAll(nueFilesWithErrors);
}
 
Example 50
Project: incubator-netbeans   File: SharableLibrariesUtils.java   Source Code and License 5 votes vote down vote up
public void actionPerformed(ActionEvent e) {
    try {
        String value = ahelper.getStandardPropertyEvaluator().evaluate(reference);
        File absFile = ahelper.resolveFile(value);
        String location = ahelper.getLibrariesLocation();
        File libraryFile = ahelper.resolveFile(location);
        File directory = libraryFile.getParentFile();
        final FileObject dir = FileUtil.createFolder(directory);
        if (!absFile.exists()) {
            //#131535 is a broken reference probably, ignore.
            return;
        }
        updateReference(absFile, reference, true, dir);
        //now process source reference
        String source = reference.replace("${file.reference", "${source.reference"); //NOI18N
        value = ahelper.getStandardPropertyEvaluator().evaluate(source);
        if (!value.startsWith("${source.")) { //NOI18N
            absFile = ahelper.resolveFile(value);
            updateReference(absFile, source.replace("${", "").replace("}", ""), false, dir);
        }
        //now process javadoc reference
        String javadoc = reference.replace("${file.reference", "${javadoc.reference"); //NOI18N
        value = ahelper.getStandardPropertyEvaluator().evaluate(javadoc);
        if (!value.startsWith("${javadoc.")) { //NOI18N
            absFile = ahelper.resolveFile(value);
            updateReference(absFile, javadoc.replace("${", "").replace("}", ""), false, dir);
        }
    } catch (IOException ioe) {
        Exceptions.printStackTrace(ioe);
    }
}
 
Example 51
Project: incubator-netbeans   File: ParsingErrorsFilter.java   Source Code and License 5 votes vote down vote up
private static void refresh(FileObject file) {
    try {
        reindexActionItems();
        reindexFile(file);
        refreshDocument(file);
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    }
}
 
Example 52
Project: incubator-netbeans   File: Nodes.java   Source Code and License 5 votes vote down vote up
public void open() {
    try {
        PositionRef pos = ed.getRange().getBegin();
        int line = pos.getLine();
        int column = pos.getColumn();
        Line l = pos.getCloneableEditorSupport().getLineSet().getCurrent(line);

        l.show(ShowOpenType.OPEN, ShowVisibilityType.FOCUS, column);
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    }
}
 
Example 53
Project: incubator-netbeans   File: PackageViewChildren.java   Source Code and License 5 votes vote down vote up
@Override
protected void removeNotify() {
    // System.out.println("REMOVE NOTIFY" + root + " : " + this );        
    VisibilityQuery.getDefault().removeChangeListener( wvqcl );
    try {
        root.getFileSystem().removeFileChangeListener( wfcl );
    }
    catch ( FileStateInvalidException e ) {
        Exceptions.printStackTrace(e);
    }
    setKeys(new String[0]);
    names2nodes.clear();
    super.removeNotify();
}
 
Example 54
Project: incubator-netbeans   File: AbstractOutputPane.java   Source Code and License 5 votes vote down vote up
public final boolean sendCaretToLine(int idx, boolean select) {
    int lastLine = getLineCount() - 1;
    if (idx > lastLine) {
        idx = lastLine;
    }
    inSendCaretToLine = true;
    try {
        getCaret().setVisible(true);
        getCaret().setSelectionVisible(true);
        Element el = textView.getDocument().getDefaultRootElement().getElement(idx);
        int position = el.getStartOffset();
        if (select) {
            getCaret().setDot(el.getEndOffset() - 1);
            getCaret().moveDot(position);
            textView.repaint();
        } else {
            getCaret().setDot(position);
        }

        if (!scrollToLine(idx + 3) && isScrollLocked()) {
            lineToScroll = idx + 3;
        }
    } catch (Error sie) {
        if (sie.getClass().getName().equals("javax.swing.text.StateInvariantError")) {
            Exceptions.attachMessage(sie, "sendCaretToLine("+idx+", "+select+"), caret = "+getCaret()+", highlighter = "+textView.getHighlighter()+", document length = "+textView.getDocument().getLength());
        }
        Exceptions.printStackTrace(sie);
    } finally {
        locked = false;
        inSendCaretToLine = false;
    }
    return true;
}
 
Example 55
Project: incubator-netbeans   File: PackageRootNode.java   Source Code and License 5 votes vote down vote up
public @Override String getHtmlDisplayName() {
     try {
        String result = file.getFileSystem().getDecorator().annotateNameHtml (
            super.getDisplayName(), files);

        //Make sure the super string was really modified
        if (result != null && !super.getDisplayName().equals(result)) {
            return result;
        }
     } catch (FileStateInvalidException e) {
         Exceptions.printStackTrace(e);
     }
     return super.getHtmlDisplayName();
}
 
Example 56
Project: incubator-netbeans   File: CodeHintProviderImpl.java   Source Code and License 5 votes vote down vote up
private Map<HintMetadata, ? extends Collection<? extends HintDescription>> computeHints(ClassLoader l, String path) {
    Map<HintMetadata, Collection<HintDescription>> result = new HashMap<HintMetadata, Collection<HintDescription>>();
    
    for (ClassWrapper c : FSWrapper.listClasses()) {
        try {
            processClass(c, result);
        } catch (ThreadDeath td) {
            throw td;
        } catch (Throwable t) {
            Exceptions.printStackTrace(t);
        }
    }

    return result;
}
 
Example 57
Project: incubator-netbeans   File: FileTreeElement.java   Source Code and License 5 votes vote down vote up
@Override
public void open() {
    try {
        if(fo.isValid()) {
            DataObject od = DataObject.find(fo);
            NbDocument.openDocument(od, 0, Line.ShowOpenType.OPEN, Line.ShowVisibilityType.FOCUS);
        }
    } catch (DataObjectNotFoundException ex) {
        Exceptions.printStackTrace(ex);
    }
}
 
Example 58
Project: incubator-netbeans   File: PersistenceManager.java   Source Code and License 5 votes vote down vote up
/** @return Local folder for TopComponents. Do not cache ti because it can change
 * during project switch. */
public FileObject getComponentsLocalFolder () throws IOException {
    try {
        FileObject compsLocalFolder = FileUtil.createFolder(
            getRootLocalFolder(), COMPS_FOLDER
        );
        return compsLocalFolder;
    } catch (IOException exc) {
        String annotation = NbBundle.getMessage(PersistenceManager.class,
            "EXC_CompsFolder", COMPS_FOLDER);
        Exceptions.attachLocalizedMessage(exc, annotation);
        throw exc;
    }
}
 
Example 59
Project: incubator-netbeans   File: ClasspathPanel.java   Source Code and License 5 votes vote down vote up
private void addClasspathActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addClasspathActionPerformed
    FileChooser chooser;
    chooser = new FileChooser(model.getBaseFolder(), null);

    FileUtil.preventFileChooserSymlinkTraversal(chooser, null);
    chooser.setFileSelectionMode (JFileChooser.FILES_AND_DIRECTORIES);
    chooser.setMultiSelectionEnabled(true);
    chooser.setDialogTitle(NbBundle.getMessage(ClasspathPanel.class, "LBL_Browse_Classpath"));
    if (lastChosenFile != null) {
        chooser.setCurrentDirectory(lastChosenFile);
    } else {
        chooser.setCurrentDirectory(model.getBaseFolder());
    }
    //#65354: prevent adding a non-folder element on the classpath:
    FileFilter fileFilter = new SimpleFileFilter (
        NbBundle.getMessage( ClasspathPanel.class, "LBL_ZipJarFolderFilter" ),   // NOI18N
        new String[] {"ZIP","JAR"} );   // NOI18N
    //#61789 on old macosx (jdk 1.4.1) these two method need to be called in this order.
    chooser.setAcceptAllFileFilterUsed( false );
    chooser.setFileFilter(fileFilter);

    if (JFileChooser.APPROVE_OPTION == chooser.showOpenDialog(this)) {
        String[] filePaths = null;
        try {
            filePaths = chooser.getSelectedPaths();
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        }
        for (String filePath : filePaths) {
            listModel.addElement(filePath);
            lastChosenFile = chooser.getCurrentDirectory();
        }
        applyChanges();
        updateButtons();
    }
}
 
Example 60
Project: incubator-netbeans   File: HtmlStructureItem.java   Source Code and License 5 votes vote down vote up
@Override
public synchronized List<? extends StructureItem> getNestedItems() {
    if (items == null) {
        //lazy load the nested items
        //we need a parser result to be able to find Element for the ElementHandle
        try {
            runTask(new Task() {
                @Override
                public void run(HtmlParserResult result) {
                    Node node = handle.resolve(result);
                    // #214628 -- getNestedItems() must not return null
                    items = new ArrayList<>();
                    if (node != null) {
                        List<OpenTag> nonVirtualChildren = gatherNonVirtualChildren(node);
                        for (OpenTag child : nonVirtualChildren) {
                            HtmlElementHandle childHandle = new HtmlElementHandle(child, handle.getFileObject());
                            items.add(new HtmlStructureItem(child, childHandle, result.getSnapshot()));
                        }
                    }
                }
            });

        } catch (ParseException ex) {
            Exceptions.printStackTrace(ex);
        }
    }
    if (items == null){
        return Collections.emptyList();
    } else {
        return items;
    }
}