public static PsiFile createFromTemplate(
      final PsiDirectory directory,
      final String name,
      String fileName,
      String templateName,
      @NonNls String... parameters)
      throws IncorrectOperationException {
    log.debug("createFromTemplate: dir:" + directory + ", filename: " + fileName);

    final FileTemplate template = FileTemplateManager.getInstance().getTemplate(templateName);

    Properties properties =
        new Properties(FileTemplateManager.getInstance().getDefaultProperties());

    String text;

    try {
      text = template.getText(properties);
    } catch (Exception e) {
      throw new RuntimeException(
          "Unable to load template for "
              + FileTemplateManager.getInstance().internalTemplateToSubject(templateName),
          e);
    }

    final PsiFileFactory factory = PsiFileFactory.getInstance(directory.getProject());

    log.debug("Create file from text");
    final PsiFile file = factory.createFileFromText(fileName, MoonFileType.MOON_FILE_TYPE, text);

    log.debug("Adding file to directory");
    return (PsiFile) directory.add(file);
  }
  @Override
  protected void setUp() throws Exception {
    LOG.debug("================== setting up " + getName() + " ==================");

    super.setUp();

    myFileSystem = LocalFileSystem.getInstance();
    assertNotNull(myFileSystem);

    myWatcher = ((LocalFileSystemImpl) myFileSystem).getFileWatcher();
    assertNotNull(myWatcher);
    assertFalse(myWatcher.isOperational());
    myWatcher.startup(myNotifier);
    assertTrue(myWatcher.isOperational());

    myAlarm = new Alarm(Alarm.ThreadToUse.POOLED_THREAD, getProject());
    myTimeout = NATIVE_PROCESS_DELAY;

    myConnection = ApplicationManager.getApplication().getMessageBus().connect();
    myConnection.subscribe(
        VirtualFileManager.VFS_CHANGES,
        new BulkFileListener.Adapter() {
          @Override
          public void after(@NotNull List<? extends VFileEvent> events) {
            synchronized (myEvents) {
              myEvents.addAll(events);
            }
          }
        });

    ((LocalFileSystemImpl) myFileSystem).cleanupForNextTest();

    LOG = FileWatcher.getLog();
    LOG.debug("================== setting up " + getName() + " ==================");
  }
  public boolean canStartNewInstance() {
    if (getErrorInfo() != null) {
      LOG.debug("Can't start new instance, if image is erroneous");
      return false;
    }

    if (myImageDetails.getBehaviour().isUseOriginal()) {
      final VmwareCloudInstance myInstance = myInstances.get(myImageDetails.getSourceName());
      if (myInstance == null) {
        return false;
      }
      return myInstance.getStatus() == InstanceStatus.STOPPED;
    }

    final boolean countStoppedVmsInLimit =
        TeamCityProperties.getBooleanOrTrue(VmwareConstants.CONSIDER_STOPPED_VMS_LIMIT)
            && myImageDetails.getBehaviour().isDeleteAfterStop();

    final List<String> consideredInstances = new ArrayList<String>();
    for (Map.Entry<String, VmwareCloudInstance> entry : myInstances.entrySet()) {
      if (entry.getValue().getStatus() != InstanceStatus.STOPPED || countStoppedVmsInLimit)
        consideredInstances.add(entry.getKey());
    }
    final boolean canStartMore = consideredInstances.size() < myImageDetails.getMaxInstances();
    LOG.debug(
        String.format(
            "Instances count: %d %s, can start more: %s",
            consideredInstances.size(),
            Arrays.toString(consideredInstances.toArray()),
            String.valueOf(canStartMore)));
    return canStartMore;
  }
  private List<VFileEvent> getEvents(String msg, @Nullable Runnable action) {
    LOG.debug("** waiting for " + msg);
    myAccept = true;

    if (action != null) {
      action.run();
    }

    int timeout = myTimeout;
    try {
      synchronized (myWaiter) {
        //noinspection WaitNotInLoop
        myWaiter.wait(timeout);
      }
    } catch (InterruptedException e) {
      LOG.warn(e);
    }

    LOG.debug("** waited for " + timeout);
    myFileSystem.refresh(false);

    ArrayList<VFileEvent> result;
    synchronized (myEvents) {
      result = new ArrayList<VFileEvent>(myEvents);
      myEvents.clear();
    }
    LOG.debug("** events: " + result.size());
    return result;
  }
Example #5
0
 @NotNull
 public static List<VcsDirectoryMapping> addMapping(
     @NotNull List<VcsDirectoryMapping> existingMappings,
     @NotNull String path,
     @NotNull String vcs) {
   List<VcsDirectoryMapping> mappings = new ArrayList<VcsDirectoryMapping>(existingMappings);
   for (Iterator<VcsDirectoryMapping> iterator = mappings.iterator(); iterator.hasNext(); ) {
     VcsDirectoryMapping mapping = iterator.next();
     if (mapping.isDefaultMapping() && StringUtil.isEmptyOrSpaces(mapping.getVcs())) {
       LOG.debug("Removing <Project> -> <None> mapping");
       iterator.remove();
     } else if (FileUtil.pathsEqual(mapping.getDirectory(), path)) {
       if (!StringUtil.isEmptyOrSpaces(mapping.getVcs())) {
         LOG.warn(
             "Substituting existing mapping ["
                 + path
                 + "] -> ["
                 + mapping.getVcs()
                 + "] with ["
                 + vcs
                 + "]");
       } else {
         LOG.debug("Removing [" + path + "] -> <None> mapping");
       }
       iterator.remove();
     }
   }
   mappings.add(new VcsDirectoryMapping(path, vcs));
   return mappings;
 }
 public static void logFile(String file, boolean isWrite) {
   ArrayList<String> cmds = new ArrayList<String>();
   cmds.add(Dependencies.getPythonLocation());
   cmds.add(Dependencies.getCLILocation());
   cmds.add("--file");
   cmds.add(file);
   String project = WakaTime.getProjectName();
   if (project != null) {
     cmds.add("--project");
     cmds.add(project);
   }
   cmds.add("--plugin");
   cmds.add(IDE_NAME + "/" + IDE_VERSION + " " + IDE_NAME + "-wakatime/" + VERSION);
   if (isWrite) cmds.add("--write");
   try {
     log.debug("Executing CLI: " + Arrays.toString(cmds.toArray()));
     Process proc = Runtime.getRuntime().exec(cmds.toArray(new String[cmds.size()]));
     if (WakaTime.DEBUG) {
       BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
       BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
       proc.waitFor();
       String s;
       while ((s = stdInput.readLine()) != null) {
         log.debug(s);
       }
       while ((s = stdError.readLine()) != null) {
         log.debug(s);
       }
       log.debug("Command finished with return value: " + proc.exitValue());
     }
   } catch (Exception e) {
     log.error(e);
   }
 }
Example #7
0
 private static void retainOnlyJarsAndDirectories(List<VirtualFile> woSdk) {
   for (Iterator<VirtualFile> iterator = woSdk.iterator(); iterator.hasNext(); ) {
     VirtualFile file = iterator.next();
     final VirtualFile local = ArchiveVfsUtil.getVirtualFileForJar(file);
     final boolean dir = file.isDirectory();
     final String name = file.getName();
     if (LOG.isDebugEnabled()) {
       LOG.debug(
           "Considering: "
               + file.getPath()
               + "; local="
               + local
               + "; dir="
               + dir
               + "; name="
               + name);
     }
     if (dir || local != null) {
       continue;
     }
     if (name.endsWith(".jar")) {
       continue;
     }
     LOG.debug("Removing");
     iterator.remove();
   }
 }
Example #8
0
  /** @return true if keymap was installed or was successfully installed */
  public static boolean installKeyBoardBindings() {
    LOG.debug("Check for keyboard bindings");
    final LocalFileSystem localFileSystem = LocalFileSystem.getInstance();
    if (localFileSystem.refreshAndFindFileByPath(KEYMAPS_PATH) == null) {
      reportError("Failed to install vim keymap. Empty keymaps folder");
      return false;
    }

    LOG.debug("No vim keyboard installed found. Installing");
    try {
      final byte[] bytes = toByteArray(retrieveSourceKeymapStream());
      Files.write(bytes, new File(INSTALLED_VIM_KEYMAP_PATH));
      final Document document = StorageUtil.loadDocument(bytes);
      if (document != null && !ApplicationManager.getApplication().isUnitTestMode()) {
        // Prompt user to select the parent for the Vim keyboard
        if (!configureVimParentKeymap(INSTALLED_VIM_KEYMAP_PATH, document, true)) {
          return false;
        }
      }
      installKeymap(document);
    } catch (IOException e) {
      reportError("Source keymap not found", e);
      return false;
    } catch (InvalidDataException e) {
      reportError("Failed to install vim keymap. Vim.xml file is corrupted", e);
      return false;
    } catch (Exception e) {
      reportError("Failed to install vim keymap.\n", e);
      return false;
    }

    return true;
  }
  public void initComponent() {
    log.info("Initializing WakaTime plugin v" + VERSION + " (https://wakatime.com/)");
    // System.out.println("Initializing WakaTime plugin v" + VERSION + " (https://wakatime.com/)");

    // Set runtime constants
    IDE_NAME = PlatformUtils.getPlatformPrefix();
    IDE_VERSION = ApplicationInfo.getInstance().getFullVersion();

    if (!Dependencies.isCLIInstalled()) {
      log.info("Downloading and installing wakatime-cli ...");
      Dependencies.installCLI();
    } else if (Dependencies.isCLIOld()) {
      log.info("Upgrading wakatime-cli ...");
      Dependencies.upgradeCLI();
    }

    if (Dependencies.isPythonInstalled()) {

      WakaTime.DEBUG = WakaTime.isDebugEnabled();
      if (WakaTime.DEBUG) {
        log.setLevel(Level.DEBUG);
        log.debug("Logging level set to DEBUG");
      }

      log.debug("Python location: " + Dependencies.getPythonLocation());
      log.debug("CLI location: " + Dependencies.getCLILocation());

      // prompt for apiKey if it does not already exist
      if (ApiKey.getApiKey().equals("")) {
        Project project = ProjectManager.getInstance().getDefaultProject();
        ApiKey apiKey = new ApiKey(project);
        apiKey.promptForApiKey();
      }
      log.debug("Api Key: " + ApiKey.getApiKey());

      // add WakaTime item to File menu
      ActionManager am = ActionManager.getInstance();
      PluginMenu action = new PluginMenu();
      am.registerAction("WakaTimeApiKey", action);
      DefaultActionGroup fileMenu = (DefaultActionGroup) am.getAction("FileMenu");
      fileMenu.addSeparator();
      fileMenu.add(action);

      // Setup message listeners
      MessageBus bus = ApplicationManager.getApplication().getMessageBus();
      connection = bus.connect();
      connection.subscribe(AppTopics.FILE_DOCUMENT_SYNC, new CustomSaveListener());
      EditorFactory.getInstance()
          .getEventMulticaster()
          .addDocumentListener(new CustomDocumentListener());

      log.debug("Finished initializing WakaTime plugin");

    } else {
      Messages.showErrorDialog(
          "WakaTime requires Python to be installed.\nYou can install it from https://www.python.org/downloads/\nAfter installing Python, restart your IDE.",
          "Error");
    }
  }
 private void logRoots(final List<VirtualFile> roots) {
   if (LOG.isDebugEnabled()) {
     LOG.debug("Roots for committed changes load:\n");
     for (VirtualFile root : roots) {
       LOG.debug(root.getPath() + ", ");
     }
   }
 }
  @Override
  @NotNull
  public String askPassword(@NotNull String url) {
    LOG.debug(
        "askPassword. url="
            + url
            + ", passwordKnown="
            + (myPassword != null)
            + ", wasCancelled="
            + myWasCancelled);
    if (myPassword != null) { // already asked in askUsername
      return myPassword;
    }
    if (myWasCancelled) { // already pressed cancel in askUsername
      return "";
    }
    myUnifiedUrl = getUnifiedUrl(url);
    Pair<GitHttpAuthDataProvider, AuthData> authData = findBestAuthData(getUnifiedUrl(url));
    if (authData != null && authData.second.getPassword() != null) {
      String password = authData.second.getPassword();
      myDataProvider = authData.first;
      myPassword = password;
      LOG.debug(
          "askPassword. dataProvider="
              + getCurrentDataProviderName()
              + ", unifiedUrl= "
              + getUnifiedUrl(url)
              + ", login="******", passwordKnown="
              + (password != null));
      return password;
    }

    myPasswordKey = getUnifiedUrl(url);
    String password =
        CredentialPromptDialog.askPassword(
            myProject,
            myTitle,
            "Password for " + getDisplayableUrl(url),
            CredentialAttributes(PASS_REQUESTER, myPasswordKey));
    LOG.debug(
        "askPassword. Password was asked and returned: "
            + (password == null ? "NULL" : password.isEmpty() ? "EMPTY" : "NOT EMPTY"));
    if (password == null) {
      myWasCancelled = true;
      return "";
    }
    // Password is stored in the safe in PasswordSafePromptDialog.askPassword,
    // but it is not the right behavior (incorrect password is stored too because of that) and
    // should be fixed separately.
    // We store it here manually, to let it work after that behavior is fixed.
    myPassword = password;
    myDataProvider =
        new GitDefaultHttpAuthDataProvider(); // workaround: askPassword remembers the password even
    // it is not correct
    return password;
  }
  private void compileFinished(int exitValue, final ModuleChunk chunk, final String outputDir) {
    if (exitValue != 0
        && !myCompileContext.getProgressIndicator().isCanceled()
        && myCompileContext.getMessageCount(CompilerMessageCategory.ERROR) == 0) {
      myCompileContext.addMessage(
          CompilerMessageCategory.ERROR,
          CompilerBundle.message("error.compiler.internal.error", exitValue),
          null,
          -1,
          -1);
    }

    myCompiler.compileFinished();
    final List<File> toRefresh = new ArrayList<File>();
    final Map<String, Collection<TranslatingCompiler.OutputItem>> results =
        new HashMap<String, Collection<TranslatingCompiler.OutputItem>>();
    try {
      final FileTypeManager typeManager = FileTypeManager.getInstance();
      final String outputDirPath = outputDir.replace(File.separatorChar, '/');
      try {
        for (final Module module : chunk.getModules()) {
          for (final VirtualFile root : chunk.getSourceRoots(module)) {
            final String packagePrefix = myProjectFileIndex.getPackageNameByDirectory(root);
            if (LOG.isDebugEnabled()) {
              LOG.debug(
                  "Building output items for "
                      + root.getPresentableUrl()
                      + "; output dir = "
                      + outputDirPath
                      + "; packagePrefix = \""
                      + packagePrefix
                      + "\"");
            }
            buildOutputItemsList(
                outputDirPath, module, root, typeManager, root, packagePrefix, toRefresh, results);
          }
        }
      } catch (CacheCorruptedException e) {
        myCompileContext.requestRebuildNextTime(
            CompilerBundle.message("error.compiler.caches.corrupted"));
        if (LOG.isDebugEnabled()) {
          LOG.debug(e);
        }
      }
    } finally {
      CompilerUtil.refreshIOFiles(toRefresh);
      for (Iterator<Map.Entry<String, Collection<TranslatingCompiler.OutputItem>>> it =
              results.entrySet().iterator();
          it.hasNext(); ) {
        Map.Entry<String, Collection<TranslatingCompiler.OutputItem>> entry = it.next();
        mySink.add(entry.getKey(), entry.getValue(), VirtualFile.EMPTY_ARRAY);
        it.remove(); // to free memory
      }
    }
    myFileNameToSourceMap.clear(); // clear the map before the next use
  }
Example #13
0
 /** Parse and print pretty-formatted XML to {@code logger}, if its level is DEBUG or below. */
 public static void prettyFormatXmlToLog(@NotNull Logger logger, @NotNull String xml) {
   if (logger.isDebugEnabled()) {
     try {
       logger.debug(
           "\n" + JDOMUtil.createOutputter("\n").outputString(JDOMUtil.loadDocument(xml)));
     } catch (Exception e) {
       logger.debug(e);
     }
   }
 }
Example #14
0
 @NotNull
 public static String getShortHash(@NotNull String hash) {
   if (hash.length() < SHORT_HASH_LENGTH) {
     LOG.debug("Unexpectedly short hash: [" + hash + "]");
   }
   if (hash.length() > LONG_HASH_LENGTH) {
     LOG.debug("Unexpectedly long hash: [" + hash + "]");
   }
   return hash.substring(0, Math.min(SHORT_HASH_LENGTH, hash.length()));
 }
Example #15
0
 /** Parse and print pretty-formatted Json to {@code logger}, if its level is DEBUG or below. */
 public static void prettyFormatJsonToLog(@NotNull Logger logger, @NotNull JsonElement json) {
   if (logger.isDebugEnabled()) {
     try {
       Gson gson = new GsonBuilder().setPrettyPrinting().create();
       logger.debug("\n" + gson.toJson(json));
     } catch (JsonSyntaxException e) {
       logger.debug("Malformed JSON\n" + json);
     }
   }
 }
 /**
  * Called after top level methods (and other items) have been moved from entries to
  * ruleInstanceList. Task now is to scan ruleInstanceList looking for MethodEntry objects with
  * dependent (related, extracted) methods. Move these from the entries list to the correct place
  * in the ruleInstanceList list.
  *
  * @param entries Remaining (unarranged) items, including all dependent (extracted) methods.
  * @param ruleInstance Rule containing parents (callers) of potentially related methods
  */
 public static void rearrangeRelatedItems(
     List<ClassContentsEntry> entries, RuleInstance ruleInstance, RelatedMethodsSettings rms) {
   List<RangeEntry> parentEntries = new ArrayList<RangeEntry>(ruleInstance.getMatches());
   for (RangeEntry o : parentEntries) {
     if (o instanceof RelatableEntry) {
       MethodEntry me = (MethodEntry) o;
       if (me.isGetter()) {
         if (me.myKeptWithProperty) {
           if (me.getMatchedRule() != null && me.getMatchedRule().getMatches() != null) {
             // prevent the getter from appearing under a rule it matches; it will be placed under
             // the property
             me.getMatchedRule().getMatches().remove(me);
           }
         }
         for (MethodEntry theSetter : me.myCorrespondingGetterSetters) {
           final RuleInstance theRule = theSetter.getMatchedRule();
           LOG.debug(
               "rearrangeRelatedItems: for getter method "
                   + me
                   + ", corresponding setter is "
                   + theSetter);
           if (theRule != null && theRule.getMatches() != null) {
             LOG.debug(
                 "remove entry "
                             + theSetter.myEnd
                             + " from matched rule"
                             + theRule
                             + "; matches = "
                             + ((java.util.List) theRule.getMatches())
                         == null
                     ? "null"
                     : "");
             theRule.getMatches().remove(theSetter);
           }
         }
       }
       if (me.myCalledMethods.size() > 0) {
         List<MethodEntry> parents = new LinkedList<MethodEntry>();
         parents.add(me);
         moveRelatedItems(
             entries,
             parents,
             rms,
             ((PsiMethod) me.myEnd).getName(),
             ((PsiMethod) me.myEnd).getName() + "()",
             1);
         if (LOG.isDebugEnabled()) {
           // dump sorted children recursively
           me.dumpChild(0);
         }
         me.assignComments(rms);
       }
     }
   }
 }
  @NotNull
  protected final PsiElement[] invokeDialog(final Project project, final PsiDirectory directory) {
    log.debug("invokeDialog");
    final MyInputValidator validator = new MyInputValidator(project, directory);
    Messages.showInputDialog(
        project, getDialogPrompt(), getDialogTitle(), Messages.getQuestionIcon(), "", validator);

    final PsiElement[] elements = validator.getCreatedElements();
    log.debug("Result: " + Arrays.toString(elements));
    return elements;
  }
  private static SourcePosition calcPosition(
      final ValueDescriptor descriptor, final DebugProcessImpl debugProcess)
      throws ClassNotLoadedException {
    final Value value = descriptor.getValue();
    if (value == null) {
      return null;
    }

    Type type = value.type();
    if (type == null) {
      return null;
    }

    try {
      if (type instanceof ArrayType) {
        type = ((ArrayType) type).componentType();
      }
      if (type instanceof ClassType) {
        final ClassType clsType = (ClassType) type;
        final List<Location> locations = clsType.allLineLocations();
        if (locations.size() > 0) {
          final Location location = locations.get(0);
          return ApplicationManager.getApplication()
              .runReadAction(
                  new Computable<SourcePosition>() {
                    @Override
                    public SourcePosition compute() {
                      SourcePosition position =
                          debugProcess.getPositionManager().getSourcePosition(location);
                      // adjust position for non-anonymous classes
                      if (clsType.name().indexOf('$') < 0) {
                        final PsiClass classAt =
                            position != null ? JVMNameUtil.getClassAt(position) : null;
                        if (classAt != null) {
                          final SourcePosition classPosition =
                              SourcePosition.createFromElement(classAt);
                          if (classPosition != null) {
                            position = classPosition;
                          }
                        }
                      }
                      return position;
                    }
                  });
        }
      }
    } catch (ClassNotPreparedException e) {
      LOG.debug(e);
    } catch (AbsentInformationException e) {
      LOG.debug(e);
    }
    return null;
  }
  private void doAction(final MyAction action) {
    LOG.debug("doAction: START " + action.name());
    final MyExitAction[] exitActions;
    List<Runnable> toBeCalled = null;
    synchronized (myLock) {
      final MyState oldState = myState;
      myState = myState.transition(action);
      if (oldState.equals(myState)) return;
      exitActions = MyTransitionAction.getExit(oldState, myState);

      LOG.debug("doAction: oldState: " + oldState.name() + ", newState: " + myState.name());

      if (LOG.isDebugEnabled() && exitActions != null) {
        final String debugExitActions =
            StringUtil.join(
                exitActions,
                new Function<MyExitAction, String>() {
                  @Override
                  public String fun(MyExitAction exitAction) {
                    return exitAction.name();
                  }
                },
                " ");
        LOG.debug("exit actions: " + debugExitActions);
      }
      if (exitActions != null) {
        for (MyExitAction exitAction : exitActions) {
          if (MyExitAction.markStart.equals(exitAction)) {
            myWaitingFinishListeners.addAll(myWaitingStartListeners);
            myWaitingStartListeners.clear();
          } else if (MyExitAction.markEnd.equals(exitAction)) {
            toBeCalled = new ArrayList<Runnable>(myWaitingFinishListeners);
            myWaitingFinishListeners.clear();
          }
        }
      }
    }
    if (exitActions != null) {
      for (MyExitAction exitAction : exitActions) {
        if (MyExitAction.submitRequestToExecutor.equals(exitAction)) {
          myAlarm.consume(myWorker);
          // myAlarm.addRequest(myWorker, ourDelay);
          // ApplicationManager.getApplication().executeOnPooledThread(myWorker);
        }
      }
    }
    if (toBeCalled != null) {
      for (Runnable runnable : toBeCalled) {
        runnable.run();
      }
    }
    LOG.debug("doAction: END " + action.name());
  }
 public static Object getField(Class objectClass, Object object, Class type, @NonNls String name) {
   try {
     final Field field = findAssignableField(objectClass, type, name);
     field.setAccessible(true);
     return field.get(object);
   } catch (NoSuchFieldException e) {
     LOG.debug(e);
     return null;
   } catch (IllegalAccessException e) {
     LOG.debug(e);
     return null;
   }
 }
  @Override
  public final void action() throws Exception {
    if (LOG.isDebugEnabled()) {
      LOG.debug("trying " + this);
    }

    final SuspendContextImpl suspendContext = getSuspendContext();
    if (suspendContext == null) {
      if (LOG.isDebugEnabled()) {
        LOG.debug("skip processing - context is null " + this);
      }
      notifyCancelled();
      return;
    }

    if (suspendContext.myInProgress) {
      suspendContext.postponeCommand(this);
    } else {
      try {
        if (!suspendContext.isResumed()) {
          suspendContext.myInProgress = true;
          contextAction(suspendContext);
        } else {
          notifyCancelled();
        }
      } finally {
        suspendContext.myInProgress = false;
        if (suspendContext.isResumed()) {
          for (SuspendContextCommandImpl postponed = suspendContext.pollPostponedCommand();
              postponed != null;
              postponed = suspendContext.pollPostponedCommand()) {
            postponed.notifyCancelled();
          }
        } else {
          SuspendContextCommandImpl postponed = suspendContext.pollPostponedCommand();
          if (postponed != null) {
            final Stack<SuspendContextCommandImpl> stack = new Stack<>();
            while (postponed != null) {
              stack.push(postponed);
              postponed = suspendContext.pollPostponedCommand();
            }
            final DebuggerManagerThreadImpl managerThread =
                suspendContext.getDebugProcess().getManagerThread();
            while (!stack.isEmpty()) {
              managerThread.pushBack(stack.pop());
            }
          }
        }
      }
    }
  }
  @Nullable
  private static PsiJavaFileStub createStub(@NotNull VirtualFile file) {
    if (file.getFileType() != JavaClassFileType.INSTANCE) return null;

    try {
      return ClsFileImpl.buildFileStub(file, file.contentsToByteArray());
    } catch (ClsFormatException e) {
      LOG.debug(e);
    } catch (IOException e) {
      LOG.debug(e);
    }
    LOG.error("Failed to build java cls class for " + file.getCanonicalPath());
    return null;
  }
  public void update(final AnActionEvent event) {
    log.debug("update");
    super.update(event);

    final Presentation presentation = event.getPresentation();
    final DataContext context = event.getDataContext();
    Module module = (Module) context.getData(LangDataKeys.MODULE.getName());

    log.debug("update: module: " + module);

    final boolean hasModule = module != null;
    presentation.setEnabled(hasModule);
    presentation.setVisible(hasModule);
  }
  public PsiElement getTarget(@NotNull final DataContext dataContext) {
    final Project project = CommonDataKeys.PROJECT.getData(dataContext);
    if (project == null) return null;

    final Editor editor = CommonDataKeys.EDITOR.getData(dataContext);
    if (LOG.isDebugEnabled()) {
      LOG.debug("editor " + editor);
    }
    if (editor != null) {
      final PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
      if (file == null) return null;

      final PsiElement targetElement =
          TargetElementUtilBase.findTargetElement(
              editor,
              TargetElementUtilBase.ELEMENT_NAME_ACCEPTED
                  | TargetElementUtilBase.REFERENCED_ELEMENT_ACCEPTED
                  | TargetElementUtilBase.LOOKUP_ITEM_ACCEPTED);
      if (LOG.isDebugEnabled()) {
        LOG.debug("target element " + targetElement);
      }
      if (targetElement instanceof PsiClass) {
        return targetElement;
      }

      final int offset = editor.getCaretModel().getOffset();
      PsiElement element = file.findElementAt(offset);
      while (element != null) {
        if (LOG.isDebugEnabled()) {
          LOG.debug("context element " + element);
        }
        if (element instanceof PsiFile) {
          if (!(element instanceof PsiClassOwner)) return null;
          final PsiClass[] classes = ((PsiClassOwner) element).getClasses();
          return classes.length == 1 ? classes[0] : null;
        }
        if (element instanceof PsiClass
            && !(element instanceof PsiAnonymousClass)
            && !(element instanceof PsiSyntheticClass)) {
          return element;
        }
        element = element.getParent();
      }

      return null;
    } else {
      final PsiElement element = CommonDataKeys.PSI_ELEMENT.getData(dataContext);
      return element instanceof PsiClass ? (PsiClass) element : null;
    }
  }
 public void readClasspath(
     JpsModule model,
     final String testPattern,
     Element classpathElement,
     JpsMacroExpander expander)
     throws IOException {
   LOG.debug("start loading classpath for " + model.getName());
   final HashSet<String> libs = new HashSet<String>();
   for (Object o : classpathElement.getChildren(EclipseXml.CLASSPATHENTRY_TAG)) {
     try {
       readClasspathEntry(
           model,
           new ArrayList<String>(),
           new ArrayList<String>(),
           new HashSet<String>(),
           testPattern,
           (Element) o,
           0,
           null,
           expander.getExpandMacroMap(),
           libs);
     } catch (ConversionException e) {
       throw new IOException(e);
     }
   }
   boolean foundSdkDependency = false;
   JpsDependenciesList dependenciesList = model.getDependenciesList();
   for (JpsDependencyElement element : dependenciesList.getDependencies()) {
     if (element instanceof JpsSdkDependency) {
       foundSdkDependency = true;
       break;
     }
   }
   if (!foundSdkDependency) {
     dependenciesList.addSdkDependency(JpsJavaSdkType.INSTANCE);
   }
   if (LOG.isDebugEnabled()) {
     String name = model.getName();
     LOG.debug(
         "finished loading classpath for "
             + name
             + " ("
             + dependenciesList.getDependencies().size()
             + " items):");
     for (JpsDependencyElement element : dependenciesList.getDependencies()) {
       LOG.debug(" [" + name + "]:" + element.toString());
     }
   }
 }
 static void log(
     ProgressIndicator progressIndicator,
     TextEditorHighlightingPass pass,
     @NonNls @NotNull Object... info) {
   if (LOG.isDebugEnabled()) {
     CharSequence docText =
         pass == null || pass.getDocument() == null
             ? ""
             : ": '" + StringUtil.first(pass.getDocument().getCharsSequence(), 10, true) + "'";
     synchronized (PassExecutorService.class) {
       String infos = StringUtil.join(info, Functions.TO_STRING(), " ");
       String message =
           StringUtil.repeatSymbol(' ', getThreadNum() * 4)
               + " "
               + pass
               + " "
               + infos
               + "; progress="
               + (progressIndicator == null ? null : progressIndicator.hashCode())
               + " "
               + (progressIndicator == null ? "?" : progressIndicator.isCanceled() ? "X" : "V")
               + docText;
       LOG.debug(message);
       // System.out.println(message);
     }
   }
 }
  public Process createProcess() throws ExecutionException {
    if (LOG.isDebugEnabled()) {
      LOG.debug("Executing [" + getCommandLineString() + "]");
    }

    List<String> commands;
    try {
      checkWorkingDirectory();

      if (StringUtil.isEmptyOrSpaces(myExePath)) {
        throw new ExecutionException(
            IdeBundle.message("run.configuration.error.executable.not.specified"));
      }

      commands = CommandLineUtil.toCommandLine(myExePath, myProgramParams.getList());
    } catch (ExecutionException e) {
      LOG.warn(e);
      throw e;
    }

    try {
      ProcessBuilder builder = new ProcessBuilder(commands);
      setupEnvironment(builder.environment());
      builder.directory(myWorkDirectory);
      builder.redirectErrorStream(myRedirectErrorStream);
      return builder.start();
    } catch (IOException e) {
      LOG.warn(e);
      throw new ProcessNotCreatedException(e.getMessage(), e, this);
    }
  }
  @Nullable
  public PsiElement[] getElements(boolean[] isCopied) {
    try {
      Transferable content = myCopyPasteManager.getContents();
      if (content == null) {
        return null;
      }

      Object transferData;
      try {
        transferData = content.getTransferData(ourDataFlavor);
      } catch (UnsupportedFlavorException e) {
        return null;
      } catch (IOException e) {
        return null;
      }

      if (!(transferData instanceof MyData)) {
        return null;
      }
      MyData dataProxy = (MyData) transferData;
      if (!Comparing.equal(dataProxy, myRecentData)) {
        return null;
      }
      if (isCopied != null) {
        isCopied[0] = myRecentData.isCopied();
      }
      return myRecentData.getElements();
    } catch (Exception e) {
      if (LOG.isDebugEnabled()) {
        LOG.debug(e);
      }
      return null;
    }
  }
Example #29
0
  public Result applyFilter(String line, int entireLength) {
    try {
      final Matcher matcher = PATTERN.matcher(line);
      if (matcher.matches()) {
        final String fileName = matcher.group(1);
        final int lineNumber = Integer.parseInt(matcher.group(2));

        final int textStartOffset = entireLength - line.length();

        final PsiShortNamesCache cache = PsiShortNamesCache.getInstance(myProject);
        final PsiFile[] psiFiles = cache.getFilesByName(fileName);

        if (psiFiles.length == 0) return null;

        final HyperlinkInfo info =
            psiFiles.length == 1
                ? new OpenFileHyperlinkInfo(myProject, psiFiles[0].getVirtualFile(), lineNumber - 1)
                : new MyHyperlinkInfo(psiFiles);

        return new Result(
            textStartOffset + matcher.start(1), textStartOffset + matcher.end(2), info);
      }
    } catch (NumberFormatException e) {
      LOG.debug(e);
    }

    return null;
  }
  public void scan() {
    List<VirtualFile> workQueue = myWorkQueue;
    myWorkQueue = new ArrayList<VirtualFile>();
    boolean hasEventsToFire = myFinishRunnable != null || !myEvents.isEmpty();

    if (!workQueue.isEmpty()) {
      LocalFileSystemImpl fs = (LocalFileSystemImpl) LocalFileSystem.getInstance();
      fs.markSuspiciousFilesDirty(workQueue);
      FileWatcher watcher = fs.getFileWatcher();

      for (VirtualFile file : workQueue) {
        NewVirtualFile nvf = (NewVirtualFile) file;
        if (!myIsRecursive
            && (!myIsAsync
                || !watcher.isWatched(
                    nvf))) { // We're unable to definitely refresh synchronously by means of file
                             // watcher.
          nvf.markDirty();
        }

        RefreshWorker worker = new RefreshWorker(file, myIsRecursive);
        long t = LOG.isDebugEnabled() ? System.currentTimeMillis() : 0;
        worker.scan();
        List<VFileEvent> events = worker.getEvents();
        if (t != 0) {
          t = System.currentTimeMillis() - t;
          LOG.debug(file + " scanned in " + t + " ms, events: " + events);
        }
        myEvents.addAll(events);
        if (!events.isEmpty()) hasEventsToFire = true;
      }
    }
    iHaveEventsToFire = hasEventsToFire;
  }