private void sendFile(DataOutputStream out) throws IOException {
   Notifications.Bus.notify(
       new Notification(Constant.GROUND_ID, "GZIP", "Zip.......", NotificationType.INFORMATION));
   GZipFile.getInstance().gzipIt(path_plugins + "main.db", path_plugins + "main.db.zip");
   File myFile = new File(path_plugins + "main.db.zip");
   Notifications.Bus.notify(
       new Notification(
           Constant.GROUND_ID,
           "Action sendFile",
           "Begin send ..... - " + myFile.length(),
           NotificationType.INFORMATION));
   out.writeInt((int) myFile.length());
   byte[] buffer = new byte[Constant.BUFFER_SIZE];
   BufferedInputStream bis = new BufferedInputStream(new FileInputStream(myFile));
   int len;
   while ((len = bis.read(buffer)) > 0) {
     out.write(buffer, 0, len);
   }
   bis.close();
   out.close();
   Notifications.Bus.notify(
       new Notification(
           Constant.GROUND_ID,
           "Notification",
           "Send file successfully!",
           NotificationType.INFORMATION));
 }
 private void notifyAboutConnectionFailure(final TaskRepository repository, String details) {
   Notifications.Bus.register(TASKS_NOTIFICATION_GROUP, NotificationDisplayType.BALLOON);
   String content = "<p><a href=\"\">Configure server...</a></p>";
   if (!StringUtil.isEmpty(details)) {
     content = "<p>" + details + "</p>" + content;
   }
   Notifications.Bus.notify(
       new Notification(
           TASKS_NOTIFICATION_GROUP,
           "Cannot connect to " + repository.getUrl(),
           content,
           NotificationType.WARNING,
           new NotificationListener() {
             public void hyperlinkUpdate(
                 @NotNull Notification notification, @NotNull HyperlinkEvent event) {
               TaskRepositoriesConfigurable configurable =
                   new TaskRepositoriesConfigurable(myProject);
               ShowSettingsUtil.getInstance().editConfigurable(myProject, configurable);
               if (!ArrayUtil.contains(repository, getAllRepositories())) {
                 notification.expire();
               }
             }
           }),
       myProject);
 }
 private void receiveFile(InputStream is, int fileSize) throws IOException {
   Notifications.Bus.notify(
       new Notification(
           Constant.GROUND_ID,
           "Action receiveFile",
           "Begin to receive file zip - " + fileSize,
           NotificationType.INFORMATION));
   int bytesRead;
   int byteCounts = 0;
   OutputStream output = new FileOutputStream(path_plugins + "main.db.zip");
   int sizeBuffer = Constant.BUFFER_SIZE;
   byte[] buffer = new byte[sizeBuffer];
   while ((bytesRead =
           is.read(buffer, 0, Math.max(sizeBuffer, Math.min(sizeBuffer, fileSize - byteCounts))))
       != -1) {
     output.write(buffer, 0, bytesRead);
     byteCounts += bytesRead;
     if (byteCounts >= fileSize) {
       break;
     }
   }
   output.close();
   Notifications.Bus.notify(
       new Notification(Constant.GROUND_ID, "GZIP", "Unzip.......", NotificationType.INFORMATION));
   GZipFile.getInstance().gunzipIt(path_plugins + "main.db.zip", path_plugins + "main.db");
   Notifications.Bus.notify(
       new Notification(
           Constant.GROUND_ID,
           "Notification",
           "Receive file successfully!",
           NotificationType.INFORMATION));
 }
  public void actionPerformed(AnActionEvent event) {
    PluginConfig config = PluginConfig.getInstance(event.getProject());
    if (!config.JNIPath.isEmpty()) {
      JNI_PATH = config.JNIPath;
    }
    if (!config.GeneratedHeaderName.isEmpty()) {
      HEADER_NAME = config.GeneratedHeaderName;
    }
    if (!config.Prefix4Variable.isEmpty()) {
      PREFIX_CL = config.Prefix4Variable;
    }

    boolean isOK = false;
    String exceptionMessage = null;
    try {
      String projectPath = event.getProject().getBasePath();
      File clHeader = new File(projectPath + JNI_PATH + HEADER_NAME);
      if (!clHeader.exists()) {
        clHeader.createNewFile();
      }
      clHeaderWriter = new BufferedWriter(new FileWriter(clHeader));

      writeHeader();

      File jniDir = new File(projectPath + JNI_PATH);
      readDir(jniDir);

      writeFooter();
      clHeaderWriter.flush();

      isOK = true;
    } catch (Exception e) {
      e.printStackTrace();
      exceptionMessage = e.getMessage();
    } finally {
      if (clHeaderWriter != null) {
        try {
          clHeaderWriter.close();
        } catch (IOException e1) {
          e1.printStackTrace();
        }
      }
      if (isOK) {
        Notifications.Bus.notify(
            new Notification(
                "OpenCLCLGenerator",
                "Success!",
                "Finish to generate OpenCL's CL files header.",
                NotificationType.INFORMATION));
      } else {
        Notifications.Bus.notify(
            new Notification(
                "OpenCLCLGenerator",
                "Failure!",
                "Fail to generate OpenCL's CL files header.\nError:" + exceptionMessage,
                NotificationType.INFORMATION));
      }
    }
  }
 private String getIPAndroid() {
   String host = "localhost";
   try {
     ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", "adb shell netcfg");
     builder.redirectErrorStream(true);
     Process p = builder.start();
     BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
     String line;
     while (true) {
       line = r.readLine();
       if (line == null) {
         break;
       }
       if (line.contains("0x00001043")) {
         //                    wlan0    UP                                192.168.1.79/24
         // 0x00001043 b4:52:7d:c5:8b:69
         int index = line.indexOf("/24");
         line = line.substring(0, index);
         index = line.lastIndexOf(" ");
         host = line.substring(index + 1);
         break;
       }
     }
   } catch (IOException e) {
     e.printStackTrace();
     Notifications.Bus.notify(
         new Notification(
             Constant.GROUND_ID, "Error getIPAndroid", e.toString(), NotificationType.ERROR));
   }
   return host;
 }
  private void checkFsSanity() {
    try {
      String path = myProject.getProjectFilePath();
      if (path == null || FileUtil.isAncestor(PathManager.getConfigPath(), path, true)) {
        return;
      }

      boolean actual = FileUtil.isFileSystemCaseSensitive(path);
      LOG.info(path + " case-sensitivity: " + actual);
      if (actual != SystemInfo.isFileSystemCaseSensitive) {
        int prefix =
            SystemInfo.isFileSystemCaseSensitive ? 1 : 0; // IDE=true -> FS=false -> prefix='in'
        String title = ApplicationBundle.message("fs.case.sensitivity.mismatch.title");
        String text = ApplicationBundle.message("fs.case.sensitivity.mismatch.message", prefix);
        Notifications.Bus.notify(
            new Notification(
                Notifications.SYSTEM_MESSAGES_GROUP_ID,
                title,
                text,
                NotificationType.WARNING,
                NotificationListener.URL_OPENING_LISTENER),
            myProject);
      }
    } catch (FileNotFoundException e) {
      LOG.warn(e);
    }
  }
 private void setupConnect(TransferType type) {
   Notifications.Bus.notify(
       new Notification(
           Constant.GROUND_ID,
           "Connecting...",
           "Connecting to " + serverName + " on port " + port,
           NotificationType.INFORMATION));
   Socket client = null;
   try {
     client = new Socket(serverName, port);
   } catch (IOException e) {
     e.printStackTrace();
     Notifications.Bus.notify(
         new Notification(
             Constant.GROUND_ID, "Error setupConnect", e.toString(), NotificationType.ERROR));
     return;
   }
   try {
     // System.out.println("Just connected to " + client.getRemoteSocketAddress());
     Notifications.Bus.notify(
         new Notification(
             Constant.GROUND_ID,
             "Socket status",
             "Connected to " + client.getRemoteSocketAddress(),
             NotificationType.INFORMATION));
     OutputStream outToServer = client.getOutputStream();
     DataOutputStream out = new DataOutputStream(outToServer);
     if (type == TransferType.RECEIVE) {
       out.writeUTF(GETFILESK_COMMAND);
       InputStream inFromServer = client.getInputStream();
       DataInputStream in = new DataInputStream(inFromServer);
       int fileSize = in.readInt();
       receiveFile(inFromServer, fileSize);
       actionOpenFile();
     } else if (type == TransferType.SEND) {
       out.writeUTF(SETFILESK_COMMAND);
       sendFile(out);
     }
     if (client != null) client.close();
   } catch (IOException e) {
     e.printStackTrace();
     Notifications.Bus.notify(
         new Notification(Constant.GROUND_ID, "Error talk", e.toString(), NotificationType.ERROR));
   }
 }
Ejemplo n.º 8
0
 private static void reportError(final String message, @Nullable final Exception e) {
   LOG.error(message, e);
   Notifications.Bus.notify(
       new Notification(
           VimPlugin.IDEAVIM_NOTIFICATION_ID,
           VimPlugin.IDEAVIM_NOTIFICATION_TITLE,
           message + String.valueOf(e),
           NotificationType.ERROR));
 }
 public ControllerTransferFile() {
   path_plugins =
       this.getClass()
           .getResource("sqlitebrowser")
           .getPath()
           .replace("file:/", "")
           .replace("SunnyPoint.jar!/sqlitebrowser", "");
   //        Messages.showErrorDialog(path_plugins + "sqlitebrowser/config.txt", "path");
   extractResource();
   Notifications.Bus.register(Constant.GROUND_ID, NotificationDisplayType.BALLOON);
 }
Ejemplo n.º 10
0
  /**
   * Changes parent keymap for the Vim
   *
   * @return true if document was changed successfully
   */
  private static boolean configureVimParentKeymap(
      final String path, @NotNull final Document document, final boolean showNotification)
      throws IOException, InvalidDataException {
    final Element rootElement = document.getRootElement();
    final String parentKeymapName = rootElement.getAttributeValue("parent");
    final VimKeymapDialog vimKeymapDialog = new VimKeymapDialog(parentKeymapName);
    vimKeymapDialog.show();
    if (vimKeymapDialog.getExitCode() != DialogWrapper.OK_EXIT_CODE) {
      return false;
    }
    rootElement.removeAttribute("parent");
    final Keymap parentKeymap = vimKeymapDialog.getSelectedKeymap();
    final String keymapName = parentKeymap.getName();
    VimKeymapConflictResolveUtil.resolveConflicts(rootElement, parentKeymap);
    // We cannot set a user-defined modifiable keymap as the parent of our Vim keymap so we have to
    // copy its shortcuts
    if (parentKeymap.canModify()) {
      final KeymapImpl vimKeyMap = new KeymapImpl();
      final KeymapManager keymapManager = KeymapManager.getInstance();
      final KeymapManagerImpl keymapManagerImpl = (KeymapManagerImpl) keymapManager;
      final Keymap[] allKeymaps = keymapManagerImpl.getAllKeymaps();
      vimKeyMap.readExternal(rootElement, allKeymaps);
      final HashSet<String> ownActions =
          new HashSet<String>(Arrays.asList(vimKeyMap.getOwnActionIds()));
      final KeymapImpl parentKeymapImpl = (KeymapImpl) parentKeymap;
      for (String parentAction : parentKeymapImpl.getOwnActionIds()) {
        if (!ownActions.contains(parentAction)) {
          final List<Shortcut> shortcuts = Arrays.asList(parentKeymap.getShortcuts(parentAction));
          rootElement.addContent(
              VimKeymapConflictResolveUtil.createActionElement(parentAction, shortcuts));
        }
      }
      final Keymap grandParentKeymap = parentKeymap.getParent();
      rootElement.setAttribute("parent", grandParentKeymap.getName());
    } else {
      rootElement.setAttribute("parent", keymapName);
    }
    VimPlugin.getInstance().setPreviousKeyMap(keymapName);
    // Save modified keymap to the file
    JDOMUtil.writeDocument(document, path, "\n");
    if (showNotification) {
      Notifications.Bus.notify(
          new Notification(
              VimPlugin.IDEAVIM_NOTIFICATION_ID,
              VimPlugin.IDEAVIM_NOTIFICATION_TITLE,
              "Successfully configured vim keymap to be based on "
                  + parentKeymap.getPresentableName(),
              NotificationType.INFORMATION));
    }

    return true;
  }
 public void run() {
   try {
     setupConnect(type);
   } catch (Exception e) {
     e.printStackTrace();
     Notifications.Bus.notify(
         new Notification(
             Constant.GROUND_ID,
             "Error run SocketClient",
             e.toString(),
             NotificationType.ERROR));
   }
 }
 public void activate() {
   if (SystemInfo.isWindows) {
     if (!SVNJNAUtil.isJNAPresent()) {
       Notifications.Bus.notify(
           new Notification(
               myVcs.getDisplayName(),
               "Subversion plugin: no JNA",
               "A problem with JNA initialization for SVNKit library. Encryption is not available.",
               NotificationType.WARNING),
           myProject);
     } else if (!SVNJNAUtil.isWinCryptEnabled()) {
       Notifications.Bus.notify(
           new Notification(
               myVcs.getDisplayName(),
               "Subversion plugin: no encryption",
               "A problem with encryption module (Crypt32.dll) initialization for SVNKit library. "
                   + "Encryption is not available.",
               NotificationType.WARNING),
           myProject);
     }
   }
 }
 public void actionSocketReceiveFile(AnActionEvent event) {
   inputIPAddr();
   try {
     extractResource();
     Thread t = new SocketClientTransferFile(TransferType.RECEIVE);
     t.start();
   } catch (Exception e) {
     e.printStackTrace();
     Notifications.Bus.notify(
         new Notification(
             Constant.GROUND_ID, "Error SocketReceiveFile", e.toString(), NotificationType.ERROR));
   }
 }
 public void extractResource() {
   try {
     // extract sqlitebrowser in jar file
     File f = new File(path_plugins + "sqlitebrowser");
     if (!f.exists()) {
       runtime.exec("cmd.exe /c cd " + path_plugins + " && jar xf SunnyPoint.jar sqlitebrowser");
     }
   } catch (IOException e) {
     e.printStackTrace();
     Notifications.Bus.notify(
         new Notification(
             Constant.GROUND_ID, "Error extract", e.toString(), NotificationType.ERROR));
   }
 }
 public void actionSocketSendFile(AnActionEvent event) {
   inputIPAddr();
   try {
     extractResource();
     Thread t = new SocketClientTransferFile(TransferType.SEND);
     t.start();
   } catch (Exception e) {
     e.printStackTrace();
     Notifications.Bus.notify(
         new Notification(
             Constant.GROUND_ID, "Error SocketSendFile", e.toString(), NotificationType.ERROR));
     //            Messages.showErrorDialog(e.toString(), "Socket error");
   }
 }
  private void showVendoringNotification() {
    if (!myModuleInitialized || myModule.isDisposed()) {
      return;
    }
    Project project = myModule.getProject();
    String version = GoSdkService.getInstance(project).getSdkVersion(myModule);
    if (!GoVendoringUtil.supportsVendoring(version)
        || GoVendoringUtil.supportsVendoringByDefault(version)) {
      return;
    }
    if (GoModuleSettings.getInstance(myModule).getVendoringEnabled() != ThreeState.UNSURE) {
      return;
    }

    PropertiesComponent propertiesComponent = PropertiesComponent.getInstance(project);
    boolean shownAlready;
    //noinspection SynchronizationOnLocalVariableOrMethodParameter
    synchronized (propertiesComponent) {
      shownAlready =
          propertiesComponent.getBoolean(GO_VENDORING_NOTIFICATION_HAD_BEEN_SHOWN, false);
      if (!shownAlready) {
        propertiesComponent.setValue(
            GO_VENDORING_NOTIFICATION_HAD_BEEN_SHOWN, String.valueOf(true));
      }
    }

    if (!shownAlready) {
      NotificationListener.Adapter notificationListener =
          new NotificationListener.Adapter() {
            @Override
            protected void hyperlinkActivated(
                @NotNull Notification notification, @NotNull HyperlinkEvent event) {
              if (event.getEventType() == HyperlinkEvent.EventType.ACTIVATED
                  && "configure".equals(event.getDescription())) {
                GoModuleSettings.showModulesConfigurable(project);
              }
            }
          };
      Notification notification =
          GoConstants.GO_NOTIFICATION_GROUP.createNotification(
              "Vendoring usage is detected",
              "<p><strong>vendor</strong> directory usually means that project uses Go Vendor Experiment.</p>\n"
                  + "<p>Selected Go SDK version support vendoring but it's disabled by default.</p>\n"
                  + "<p>You may want to explicitly enabled Go Vendor Experiment in the <a href='configure'>project settings</a>.</p>",
              NotificationType.INFORMATION,
              notificationListener);
      Notifications.Bus.notify(notification, project);
    }
  }
  public static void reportPluginError() {
    if (myPluginError != null) {
      String title = IdeBundle.message("title.plugin.error");
      Notifications.Bus.notify(
          new Notification(
              title,
              title,
              myPluginError,
              NotificationType.ERROR,
              new NotificationListener() {
                @SuppressWarnings("AssignmentToStaticFieldFromInstanceMethod")
                @Override
                public void hyperlinkUpdate(
                    @NotNull Notification notification, @NotNull HyperlinkEvent event) {
                  notification.expire();

                  String description = event.getDescription();
                  if (EDIT.equals(description)) {
                    PluginManagerConfigurable configurable =
                        new PluginManagerConfigurable(PluginManagerUISettings.getInstance());
                    IdeFrame ideFrame = WindowManagerEx.getInstanceEx().findFrameFor(null);
                    ShowSettingsUtil.getInstance()
                        .editConfigurable((JFrame) ideFrame, configurable);
                    return;
                  }

                  List<String> disabledPlugins = getDisabledPlugins();
                  if (myPlugins2Disable != null && DISABLE.equals(description)) {
                    for (String pluginId : myPlugins2Disable) {
                      if (!disabledPlugins.contains(pluginId)) {
                        disabledPlugins.add(pluginId);
                      }
                    }
                  } else if (myPlugins2Enable != null && ENABLE.equals(description)) {
                    disabledPlugins.removeAll(myPlugins2Enable);
                  }

                  try {
                    saveDisabledPlugins(disabledPlugins, false);
                  } catch (IOException ignore) {
                  }

                  myPlugins2Enable = null;
                  myPlugins2Disable = null;
                }
              }));
      myPluginError = null;
    }
  }
Ejemplo n.º 18
0
  /** @return true if keymap was switched successfully, false otherwise */
  public static boolean switchKeymapBindings(final boolean enableVimKeymap) {
    LOG.debug("Enabling keymap");

    // In case if Vim keymap is already in use or we don't need it, we have nothing to do
    if (isVimKeymapUsed() == enableVimKeymap) {
      return false;
    }

    final KeymapManagerImpl manager = (KeymapManagerImpl) KeymapManager.getInstance();
    // Get keymap to enable
    final String keymapName2Enable =
        enableVimKeymap ? VIM_KEYMAP_NAME : VimPlugin.getInstance().getPreviousKeyMap();
    if (keymapName2Enable.isEmpty()) {
      return false;
    }
    if (keymapName2Enable.equals(manager.getActiveKeymap().getName())) {
      return false;
    }

    LOG.debug("Enabling keymap:" + keymapName2Enable);
    final Keymap keymap = manager.getKeymap(keymapName2Enable);
    if (keymap == null) {
      reportError("Failed to enable keymap: " + keymapName2Enable);
      return false;
    }

    // Save previous keymap to enable after VIM emulation is turned off
    if (enableVimKeymap) {
      VimPlugin.getInstance().setPreviousKeyMap(manager.getActiveKeymap().getName());
    }

    manager.setActiveKeymap(keymap);

    final String keyMapPresentableName = keymap.getPresentableName();
    Notifications.Bus.notify(
        new Notification(
            VimPlugin.IDEAVIM_NOTIFICATION_ID,
            VimPlugin.IDEAVIM_NOTIFICATION_TITLE,
            keyMapPresentableName + " keymap was successfully enabled",
            NotificationType.INFORMATION));
    LOG.debug(keyMapPresentableName + " keymap was successfully enabled");
    return true;
  }
Ejemplo n.º 19
0
  private boolean checkLookAndFeel(final UIManager.LookAndFeelInfo lafInfo, final boolean confirm) {
    String message = null;

    if (lafInfo.getName().contains("GTK")
        && SystemInfo.isXWindow
        && !SystemInfo.isJavaVersionAtLeast("1.6.0_12")) {
      message = IdeBundle.message("warning.problem.laf.1");
    }

    if (message != null) {
      if (confirm) {
        final String[] options = {
          IdeBundle.message("confirm.set.look.and.feel"), CommonBundle.getCancelButtonText()
        };
        final int result =
            Messages.showOkCancelDialog(
                message,
                CommonBundle.getWarningTitle(),
                options[0],
                options[1],
                Messages.getWarningIcon());
        if (result == Messages.OK) {
          myLastWarning = message;
          return true;
        }
        return false;
      }

      if (!message.equals(myLastWarning)) {
        Notifications.Bus.notify(
            new Notification(
                Notifications.SYSTEM_MESSAGES_GROUP_ID,
                "L&F Manager",
                message,
                NotificationType.WARNING,
                NotificationListener.URL_OPENING_LISTENER));
        myLastWarning = message;
      }
    }

    return true;
  }
  public void actionOpenFile() {
    try {
      extractResource();
      File f = new File(path_plugins + "sqlitebrowser");
      if (f.exists() && f.isDirectory()) {
        runtime.exec("TASKKILL /F /IM sqliteman.exe");
        runtime.exec(
            path_plugins
                + "sqlitebrowser/getdb.exe "
                + Constant.COMMAND_GETFILE
                + " "
                + path_plugins);
      }

    } catch (Exception e) {
      e.printStackTrace();
      Notifications.Bus.notify(
          new Notification(
              Constant.GROUND_ID, "Error actionOpenFile", e.toString(), NotificationType.ERROR));
    }
  }
  @Override
  public void actionPerformed(AnActionEvent e) {
    final DataContext dataContext = e.getDataContext();
    final Project project = CommonDataKeys.PROJECT.getData(dataContext);
    List<String> fileNames = findTestDataFiles(dataContext);
    if (fileNames == null || fileNames.isEmpty()) {
      String message = "Cannot find testdata files for class";
      final Notification notification =
          new Notification(
              "testdata", "Found no testdata files", message, NotificationType.INFORMATION);
      Notifications.Bus.notify(notification, project);
    } else {
      final Editor editor = e.getData(CommonDataKeys.EDITOR);
      final JBPopupFactory popupFactory = JBPopupFactory.getInstance();
      final RelativePoint point =
          editor != null
              ? popupFactory.guessBestPopupLocation(editor)
              : popupFactory.guessBestPopupLocation(dataContext);

      TestDataNavigationHandler.navigate(point, fileNames, project);
    }
  }
  private static void showNotification(@NotNull Project project) {
    PropertiesComponent propertiesComponent = PropertiesComponent.getInstance();
    PropertiesComponent projectPropertiesComponent = PropertiesComponent.getInstance(project);
    boolean shownAlready;
    //noinspection SynchronizationOnLocalVariableOrMethodParameter
    synchronized (propertiesComponent) {
      shownAlready =
          propertiesComponent.getBoolean(GO_LIBRARIES_NOTIFICATION_HAD_BEEN_SHOWN, false)
              || projectPropertiesComponent.getBoolean(
                  GO_LIBRARIES_NOTIFICATION_HAD_BEEN_SHOWN, false);
      if (!shownAlready) {
        propertiesComponent.setValue(
            GO_LIBRARIES_NOTIFICATION_HAD_BEEN_SHOWN, String.valueOf(true));
      }
    }

    if (!shownAlready) {
      NotificationListener.Adapter notificationListener =
          new NotificationListener.Adapter() {
            @Override
            protected void hyperlinkActivated(
                @NotNull Notification notification, @NotNull HyperlinkEvent event) {
              if (event.getEventType() == HyperlinkEvent.EventType.ACTIVATED
                  && "configure".equals(event.getDescription())) {
                GoLibrariesConfigurableProvider.showModulesConfigurable(project);
              }
            }
          };
      Notification notification =
          GoConstants.GO_NOTIFICATION_GROUP.createNotification(
              "GOPATH was detected",
              "We've detected some libraries from your GOPATH.\n"
                  + "You may want to add extra libraries in <a href='configure'>Go Libraries configuration</a>.",
              NotificationType.INFORMATION,
              notificationListener);
      Notifications.Bus.notify(notification, project);
    }
  }
 static void fail(@NotNull Project project, @NotNull String title, @NotNull String message) {
   Notifications.Bus.notify(
       new Notification(BnfConstants.GENERATION_GROUP, title, message, NotificationType.ERROR),
       project);
   throw new ProcessCanceledException();
 }
Ejemplo n.º 24
0
 public static void showError(Project project, String title, Throwable e) {
   MavenLog.LOG.warn(title, e);
   Notifications.Bus.notify(
       new Notification(MAVEN_NOTIFICATION_GROUP, title, e.getMessage(), NotificationType.ERROR),
       project);
 }
Ejemplo n.º 25
0
  @Override
  public void activate() {
    createPool();
    final ProjectLevelVcsManager vcsManager = ProjectLevelVcsManager.getInstance(myProject);
    if (!myProject.isDefault()) {
      ChangeListManager.getInstance(myProject).addChangeListListener(myChangeListListener);
      vcsManager.addVcsListener(myVcsListener);
    }

    SvnApplicationSettings.getInstance().svnActivated();
    if (myEntriesFileListener != null) {
      VirtualFileManager.getInstance().addVirtualFileListener(myEntriesFileListener);
    }
    // this will initialize its inner listener for committed changes upload
    LoadedRevisionsCache.getInstance(myProject);
    FrameStateManager.getInstance().addListener(myFrameStateListener);

    myAuthNotifier.init();
    mySvnBranchPointsCalculator = new SvnBranchPointsCalculator(myProject);
    mySvnBranchPointsCalculator.activate();

    if (SystemInfo.isWindows) {
      if (!SVNJNAUtil.isJNAPresent()) {
        Notifications.Bus.notify(
            new Notification(
                getDisplayName(),
                "Subversion plugin: no JNA",
                "A problem with JNA initialization for svnkit library. Encryption is not available.",
                NotificationType.WARNING),
            NotificationDisplayType.BALLOON,
            myProject);
      } else if (!SVNJNAUtil.isWinCryptEnabled()) {
        Notifications.Bus.notify(
            new Notification(
                getDisplayName(),
                "Subversion plugin: no encryption",
                "A problem with encryption module (Crypt32.dll) initialization for svnkit library. Encryption is not available.",
                NotificationType.WARNING),
            NotificationDisplayType.BALLOON,
            myProject);
      }
    }

    final SvnConfiguration.UseAcceleration accelerationType =
        SvnConfiguration.getInstance(myProject).myUseAcceleration;
    if (SvnConfiguration.UseAcceleration.javaHL.equals(accelerationType)) {
      CheckJavaHL.runtimeCheck(myProject);
    } else if (SvnConfiguration.UseAcceleration.commandLine.equals(accelerationType)
        && !ApplicationManager.getApplication().isHeadlessEnvironment()) {
      myChecker.checkExecutableAndNotifyIfNeeded();
    }

    // do one time after project loaded
    StartupManager.getInstance(myProject)
        .runWhenProjectIsInitialized(
            new DumbAwareRunnable() {
              @Override
              public void run() {
                postStartup();

                // for IDEA, it takes 2 minutes - and anyway this can be done in background, no
                // sense...
                // once it could be mistaken about copies for 2 minutes on start...

                /*if (! myMapping.getAllWcInfos().isEmpty()) {
                  invokeRefreshSvnRoots();
                  return;
                }
                ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() {
                  public void run() {
                    myCopiesRefreshManager.getCopiesRefresh().ensureInit();
                  }
                }, SvnBundle.message("refreshing.working.copies.roots.progress.text"), true, myProject);*/
              }
            });

    vcsManager.addVcsListener(myRootsToWorkingCopies);

    myLoadedBranchesStorage.activate();
  }
  @Override
  public void initComponent() {
    ProjectJdkTable jdkTable = ProjectJdkTable.getInstance();
    List<Sdk> sdkList = new ArrayList<Sdk>();

    sdkList.addAll(GoSdkUtil.getSdkOfType(GoSdkType.getInstance(), jdkTable));

    for (Sdk sdk : sdkList) {
      GoSdkData sdkData = (GoSdkData) sdk.getSdkAdditionalData();

      boolean needsUpgrade = sdkData == null;
      try {
        if (!needsUpgrade) {
          sdkData.checkValid();
        }
      } catch (ConfigurationException ex) {
        needsUpgrade = true;
      }

      if (!needsUpgrade) continue;

      needsUpgrade = false;
      GoSdkData data = GoSdkUtil.testGoogleGoSdk(sdk.getHomePath());

      if (data == null) needsUpgrade = true;

      try {
        if (data != null) {
          data.checkValid();
        }
      } catch (ConfigurationException ex) {
        needsUpgrade = true;
      }

      if (needsUpgrade) {
        Notifications.Bus.notify(
            new Notification(
                "Go SDK validator",
                "Corrupt Go SDK",
                getContent("Go", sdk.getName()),
                NotificationType.WARNING),
            myProject);
      }

      SdkModificator sdkModificator = sdk.getSdkModificator();
      sdkModificator.setSdkAdditionalData(data);
      sdkModificator.commitChanges();
    }

    sdkList.clear();
    sdkList.addAll(GoSdkUtil.getSdkOfType(GoAppEngineSdkType.getInstance(), jdkTable));

    Boolean hasGAESdk = sdkList.size() > 0;

    for (Sdk sdk : sdkList) {
      GoAppEngineSdkData sdkData = (GoAppEngineSdkData) sdk.getSdkAdditionalData();

      if (sdkData == null || sdkData.TARGET_ARCH == null || sdkData.TARGET_OS == null) {
        Notifications.Bus.notify(
            new Notification(
                "Go AppEngine SDK validator",
                "Corrupt Go App Engine SDK",
                getContent("Go App Engine", sdk.getName()),
                NotificationType.WARNING),
            myProject);

        continue;
      }

      boolean needsUpgrade = false;
      try {
        sdkData.checkValid();
      } catch (ConfigurationException ex) {
        needsUpgrade = true;
      }

      if (!needsUpgrade) continue;

      needsUpgrade = false;
      GoAppEngineSdkData data = GoSdkUtil.testGoAppEngineSdk(sdk.getHomePath());

      if (data == null) needsUpgrade = true;

      try {
        if (data != null) {
          data.checkValid();
        }
      } catch (ConfigurationException ex) {
        needsUpgrade = true;
      }

      // GAE SDK auto-update needs a bit more love
      if (data != null && !(new File(data.GOAPP_BIN_PATH)).exists()) {
        needsUpgrade = true;
      }

      if (needsUpgrade) {
        Notifications.Bus.notify(
            new Notification(
                "Go AppEngine SDK validator",
                "Corrupt Go App Engine SDK",
                getContent("Go AppEngine", sdk.getName()),
                NotificationType.WARNING),
            myProject);
      }

      SdkModificator sdkModificator = sdk.getSdkModificator();
      sdkModificator.setSdkAdditionalData(data);
      sdkModificator.commitChanges();
    }

    if (hasGAESdk) {
      String sysAppEngineDevServerPath = GoSdkUtil.getAppEngineDevServer();
      if (sysAppEngineDevServerPath.isEmpty())
        Notifications.Bus.notify(
            new Notification(
                "Go AppEngine SDK validator",
                "Problem with env variables",
                getInvalidAPPENGINE_DEV_APPSERVEREnvMessage(),
                NotificationType.WARNING,
                NotificationListener.URL_OPENING_LISTENER),
            myProject);
    }

    PluginDescriptor pluginDescriptor =
        PluginManager.getPlugin(PluginId.getId("ro.redeul.google.go"));
    if (pluginDescriptor != null) {
      String version = ((IdeaPluginDescriptorImpl) pluginDescriptor).getVersion();

      if (version.endsWith("-dev")
          && !System.getProperty("go.skip.dev.warn", "false").equals("true")) {
        Notifications.Bus.notify(
            new Notification(
                "Go plugin notice",
                "Development version detected",
                getDevVersionMessage(),
                NotificationType.WARNING,
                null),
            myProject);
      }
    }

    super.initComponent();
  }
Ejemplo n.º 27
0
  public void startProcessing() {
    ApplicationManager.getApplication()
        .runReadAction(
            new Runnable() {
              @Override
              public void run() {

                // NOTE: This tells the test runner that we’re actually going to do something
                testRunStarted();

                // NOTE: This creates the tree in the UI by sending testSuiteStarted() and
                // testStarted() messages
                DUnitTestFramework unitTestFramework = new DUnitTestFramework();

                try {
                  PsiFile psiFile =
                      PsiManager.getInstance(project).findFile(configuration.getDFile());
                  Collection<DLanguageClassDeclaration> cds =
                      PsiTreeUtil.findChildrenOfType(psiFile, DLanguageClassDeclaration.class);
                  for (DLanguageClassDeclaration cd : cds) {

                    // if a class contains the UnitTest mixin assume its a valid d-unit test class
                    String testClassName = null;
                    Collection<DLanguageTemplateMixin> tmis =
                        PsiTreeUtil.findChildrenOfType(cd, DLanguageTemplateMixin.class);
                    for (DLanguageTemplateMixin tmi : tmis) {
                      if (tmi.getText().contains("UnitTest")) {
                        DLanguageIdentifier classIdentifier = cd.getIdentifier();
                        if (classIdentifier != null) {
                          testClassName = classIdentifier.getText();
                        }
                      }
                    }

                    // find methods for the class
                    Set<String> testMethodNames = new LinkedHashSet<>();
                    Collection<DLanguageFuncDeclaration> fds =
                        PsiTreeUtil.findChildrenOfType(cd, DLanguageFuncDeclaration.class);
                    for (DLanguageFuncDeclaration fd : fds) {
                      if (testClassName != null) {
                        // only add methods with @Test
                        if (isTestMethod(fd) || isIgnoreMethod(fd)) {
                          testMethodNames.add(fd.getIdentifier().getText());
                        }
                      }
                    }

                    // add class and corresponding methods to the map
                    if (testClassName != null && !testMethodNames.isEmpty()) {
                      testClassToTestMethodNames.put(testClassName, testMethodNames);
                    }
                  }

                } catch (RuntimeConfigurationError runtimeConfigurationError) {
                  runtimeConfigurationError.printStackTrace();
                }
              }

              // NOTE: After this, actual run your tests and, as results come back, call:
              //   testFinished() when a test method finishes successfully
              //   testFailed() when a test method finishes with a failure
              //   testIgnored() when a test method is skipped for any reason
              //   testSuiteFinished() when all methods in a test class finish
              //   testRunFinished() when all tests have completed
              //   testRunCanceled() if the user has canceled the run if you need to clean up
              // anything
              //   testStdOut() to print the output from a test class/method to the console view for
              // review
              //            }
            });

    // get d-unit path
    final String dunitPath = getDUnitPath();

    if (dunitPath == null) {
      String message =
          "Please add d-unit to your dub.json/dub.sdl and run Tools > Process D Libraries";
      Notifications.Bus.notify(
          new Notification(
              "Execute Tests", "No d-unit dependency found", message, NotificationType.ERROR),
          project);
      LOG.warn(message);
    } else {
      // Actually run tests in separate runnable to avoid blocking the GUI
      ApplicationManager.getApplication()
          .executeOnPooledThread(
              new Runnable() {

                @Override
                public void run() {
                  for (Object o : testClassToTestMethodNames.entrySet()) {
                    Map.Entry pair = (Map.Entry) o;
                    String className = (String) pair.getKey();
                    Set<String> methodNames = (Set<String>) pair.getValue();

                    testSuiteStarted(className, methodNames.size());

                    for (String testMethodName : methodNames) {
                      testStarted(className, testMethodName);
                      executeTest(className, testMethodName, dunitPath);
                    }

                    testSuiteFinished(className, 0);
                  }

                  testRunFinished();
                }
              });
    }
  }
Ejemplo n.º 28
0
  private void executeTest(String className, String testMethodName, String dunitPath) {
    String testPath = className + "." + testMethodName;
    final String workingDirectory = project.getBasePath();
    //            final String testFile = configuration.getDFile().getCanonicalPath();

    final String dubPath = ToolKey.DUB_KEY.getPath(project);
    if (dubPath == null || dubPath.isEmpty()) {
      Notifications.Bus.notify(
          new Notification(
              "Dunit Test Runner",
              "Dub path must be specified",
              "Dub executable path is empty"
                  + "<br/><a href='configureDLanguageTools'>Configure</a>",
              NotificationType.WARNING,
              new DToolsNotificationListener(project)),
          project);
      return;
    }

    GeneralCommandLine commandLine = new GeneralCommandLine();
    commandLine.setWorkDirectory(workingDirectory);
    commandLine.setExePath(dubPath);
    ParametersList parametersList = commandLine.getParametersList();
    parametersList.addParametersString("--");
    parametersList.addParametersString("-v");
    parametersList.addParametersString("--filter");
    parametersList.addParametersString(testPath + "$"); // regex to locate exact test

    final StringBuilder builder = new StringBuilder();
    try {
      OSProcessHandler process = new OSProcessHandler(commandLine.createProcess());
      process.addProcessListener(
          new ProcessAdapter() {
            @Override
            public void onTextAvailable(ProcessEvent event, Key outputType) {
              builder.append(event.getText());
            }
          });

      process.startNotify();
      process.waitFor();

    } catch (ExecutionException e) {
      e.printStackTrace();
    }

    String result = builder.toString();
    // call either finished(success) or failed
    String successPatternString = ".*OK:.*";
    Pattern successPattern = Pattern.compile(successPatternString);
    Matcher successMatcher = successPattern.matcher(result);

    if (successMatcher.find()) {
      testFinished(className, testMethodName, 0);
      testStdOut(className, testMethodName, result);
    } else if (result.contains("FAILURE:")) {
      testFailed(className, testMethodName, 0, "Failed", result);
    } else if (result.contains("SKIP:")) {
      testIgnored(className, testMethodName);
      testStdOut(className, testMethodName, result);
    } else {
      testFailed(className, testMethodName, 0, "Failed for unknown reasons", result);
    }
  }
  @Override
  public void connect(String url) throws Exception {
    URI uri = new URI(url);
    setConnected(false);

    String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
    final String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
    final int port;
    if (uri.getPort() == -1) {
      if ("http".equalsIgnoreCase(scheme)) {
        port = 80;
      } else if ("https".equalsIgnoreCase(scheme)) {
        port = 443;
      } else {
        port = -1;
      }
    } else {
      port = uri.getPort();
    }

    if (!"ws".equalsIgnoreCase(scheme) && !"wss".equalsIgnoreCase(scheme)) {
      Notifications.Bus.notify(
          new Notification(
              "Websocket Client",
              "Unable to connect",
              "Only WS(S) is supported.",
              NotificationType.ERROR));
      return;
    }

    EventLoopGroup group = new NioEventLoopGroup();
    try {
      WebSocketClientHandshaker handshaker =
          WebSocketClientHandshakerFactory.newHandshaker(
              uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders());
      WebSocketClientHandler webSocketClientHandler = new WebSocketClientHandler(handshaker);

      Bootstrap bootstrap = new Bootstrap();
      bootstrap
          .group(group)
          .channel(NioSocketChannel.class)
          .handler(
              new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) {
                  ChannelPipeline p = ch.pipeline();

                  p.addLast(
                      new HttpClientCodec(),
                      new HttpObjectAggregator(8192),
                      webSocketClientHandler);
                }
              });

      channel = bootstrap.connect(uri.getHost(), port).sync().channel();
      webSocketClientHandler.handshakeFuture().sync();
      setConnected(true);

      for (; ; ) ;
    } finally {
      group.shutdownGracefully();
      setConnected(false);
    }
  }