Esempio n. 1
2
 /**
  * This function is used to re-run the analyser, and re-create the rows corresponding the its
  * results.
  */
 private void refreshReviewTable() {
   reviewPanel.removeAll();
   rows.clear();
   GridBagLayout gbl = new GridBagLayout();
   reviewPanel.setLayout(gbl);
   GridBagConstraints gbc = new GridBagConstraints();
   gbc.fill = GridBagConstraints.HORIZONTAL;
   gbc.gridy = 0;
   try {
     Map<String, Long> sums =
         analyser.processLogFile(config.getLogFilename(), fromDate.getDate(), toDate.getDate());
     for (Entry<String, Long> entry : sums.entrySet()) {
       String project = entry.getKey();
       double hours = 1.0 * entry.getValue() / (1000 * 3600);
       addRow(gbl, gbc, project, hours);
     }
     for (String project : main.getProjectsTree().getTopLevelProjects())
       if (!rows.containsKey(project)) addRow(gbl, gbc, project, 0);
     gbc.insets = new Insets(10, 0, 0, 0);
     addLeftLabel(gbl, gbc, "TOTAL");
     gbc.gridx = 1;
     gbc.weightx = 1;
     totalLabel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 3));
     gbl.setConstraints(totalLabel, gbc);
     reviewPanel.add(totalLabel);
     gbc.weightx = 0;
     addRightLabel(gbl, gbc);
   } catch (IOException e) {
     e.printStackTrace();
   }
   recomputeTotal();
   pack();
 }
    private String buildLabelText(
        @NotNull final String text,
        @NotNull final Map<TextRange, ParameterInfoUIContextEx.Flag> flagsMap) {
      final StringBuilder labelText = new StringBuilder(text);
      final String disabledTag = FLAG_TO_TAG.get(ParameterInfoUIContextEx.Flag.DISABLE);

      final Map<Integer, Integer> faultMap = new HashMap<>();
      if (isDisabledBeforeHighlight) {
        final String tag = getTag(disabledTag);
        labelText.insert(0, tag);
        faultMap.put(0, tag.length());
      }

      for (Map.Entry<TextRange, ParameterInfoUIContextEx.Flag> entry : flagsMap.entrySet()) {
        final TextRange highlightRange = entry.getKey();
        final ParameterInfoUIContextEx.Flag flag = entry.getValue();

        final String tagValue = FLAG_TO_TAG.get(flag);
        final String tag = getTag(tagValue);

        int startOffset = highlightRange.getStartOffset();
        int endOffset = highlightRange.getEndOffset() + tag.length();

        for (Map.Entry<Integer, Integer> entry1 : faultMap.entrySet()) {
          if (entry1.getKey() < highlightRange.getStartOffset()) {
            startOffset += entry1.getValue();
          }
          if (entry1.getKey() < highlightRange.getEndOffset()) {
            endOffset += entry1.getValue();
          }
        }

        if (flag == ParameterInfoUIContextEx.Flag.HIGHLIGHT && isDisabledBeforeHighlight) {
          final String disableCloseTag = getClosingTag(disabledTag);
          labelText.insert(startOffset, disableCloseTag);
          faultMap.put(highlightRange.getStartOffset(), disableCloseTag.length());
        }

        labelText.insert(startOffset, tag);
        faultMap.put(highlightRange.getStartOffset(), tag.length());

        final String endTag = getClosingTag(tagValue);
        labelText.insert(endOffset, endTag);
        faultMap.put(highlightRange.getEndOffset(), endTag.length());
      }
      return XmlStringUtil.wrapInHtml(labelText);
    }
 /**
  * Prepare branch descriptors for existing configuration
  *
  * @param target the target
  * @param roots the vcs root
  * @return the list of branch descriptors
  * @throws VcsException in case of error
  */
 private List<BranchDescriptor> prepareBranchDescriptors(
     BranchConfiguration target, List<VirtualFile> roots) throws VcsException {
   Map<String, String> map =
       target == null ? Collections.<String, String>emptyMap() : target.getReferences();
   List<BranchDescriptor> rc = new ArrayList<BranchDescriptor>();
   for (VirtualFile root : roots) {
     BranchDescriptor d = new BranchDescriptor();
     d.root = root;
     d.storedReference = map.remove(root.getPath());
     if (d.storedReference != null) {
       d.storedRoot = d.root.getPath();
     }
     d.currentReference = myConfig.describeRoot(root);
     if (d.storedReference != null && !myModify) {
       d.referenceToCheckout = d.storedReference;
     } else {
       d.referenceToCheckout = d.currentReference;
     }
     Branch.listAsStrings(myProject, root, false, true, d.existingBranches, null);
     Branch.listAsStrings(myProject, root, true, true, d.referencesToSelect, null);
     d.updateStatus();
     rc.add(d);
   }
   for (Map.Entry<String, String> m : map.entrySet()) {
     String root = m.getKey();
     String ref = m.getValue();
     BranchDescriptor d = new BranchDescriptor();
     d.storedReference = ref;
     d.storedRoot = root;
     d.referenceToCheckout = ref;
     d.updateStatus();
     rc.add(d);
   }
   return rc;
 }
  /**
   * Returns the set of data that user has entered through this wizard.
   *
   * @return Iterator
   */
  public Iterator<Map.Entry<String, String>> getSummary() {
    Map<String, String> summaryTable = new Hashtable<String, String>();

    summaryTable.put("User ID", registration.getUserID());

    return summaryTable.entrySet().iterator();
  }
 private GeoPoint[] sortPoints(GeoPoint... geoPoints) {
   Map<GeoPoint, Integer> pointCount = new LinkedHashMap<GeoPoint, Integer>();
   for (GeoPoint gp : geoPoints) {
     if (pointCount.containsKey(gp)) {
       pointCount.put(gp, pointCount.get(gp) + 1);
     } else {
       pointCount.put(gp, 1);
     }
   }
   GeoPoint center = null;
   GeoPoint end[] = new GeoPoint[2];
   GeoPoint side[] = new GeoPoint[4];
   int endIdx = 0;
   int sieIdx = 0;
   for (Map.Entry<GeoPoint, Integer> entry : pointCount.entrySet()) {
     switch (entry.getValue()) {
       case 4:
         assert center == null;
         center = entry.getKey();
         break;
       case 2:
         assert endIdx < end.length;
         end[endIdx++] = entry.getKey();
         break;
       case 1:
         assert sieIdx < side.length;
         side[sieIdx++] = entry.getKey();
         break;
     }
   }
   return new GeoPoint[] {center, end[0], side[0], side[1], end[1], side[3], side[2]};
 }
    @Override
    public synchronized void dispose() {

      for (Map.Entry<File, Jp2File> entry : openFiles.entrySet()) {
        System.out.println("closing " + entry.getKey());
        try {
          final Jp2File jp2File = entry.getValue();
          if (jp2File.stream != null) {
            jp2File.stream.close();
            jp2File.stream = null;
          }
        } catch (IOException e) {
          // warn
        }
      }

      for (File file : openFiles.keySet()) {
        System.out.println("deleting " + file);
        if (!file.delete()) {
          // warn
        }
      }

      openFiles.clear();

      if (!cacheDir.delete()) {
        // warn
      }
    }
 @NotNull
 public RangeHighlighter[] getHighlighters(@NotNull Editor editor) {
   Map<RangeHighlighter, HighlightInfo> highlightersMap = getHighlightInfoMap(editor, false);
   if (highlightersMap == null) return RangeHighlighter.EMPTY_ARRAY;
   Set<RangeHighlighter> set = new HashSet<RangeHighlighter>();
   for (Map.Entry<RangeHighlighter, HighlightInfo> entry : highlightersMap.entrySet()) {
     HighlightInfo info = entry.getValue();
     if (info.editor.equals(editor)) set.add(entry.getKey());
   }
   return set.toArray(new RangeHighlighter[set.size()]);
 }
 private PropertiesFile getSelectedPropertiesFile() {
   if (mySelectedEditor == null) return null;
   PropertiesFile selectedFile = null;
   for (Map.Entry<PropertiesFile, Editor> entry : myEditors.entrySet()) {
     Editor editor = entry.getValue();
     if (editor == mySelectedEditor) {
       selectedFile = entry.getKey();
       break;
     }
   }
   return selectedFile;
 }
 @Nullable
 public InnerSearchableConfigurable findSubConfigurable(@NotNull final Class pageClass) {
   if (mySubPanelFactories == null) {
     buildConfigurables();
   }
   for (Map.Entry<ColorAndFontPanelFactory, InnerSearchableConfigurable> entry :
       mySubPanelFactories.entrySet()) {
     if (pageClass.isInstance(entry.getValue().createPanel().getSettingsPage())) {
       return entry.getValue();
     }
   }
   return null;
 }
 @NotNull
 private Set<Usage> getReadOnlyUsages() {
   final Set<Usage> result = new THashSet<Usage>();
   final Set<Map.Entry<Usage, UsageNode>> usages = myUsageNodes.entrySet();
   for (Map.Entry<Usage, UsageNode> entry : usages) {
     Usage usage = entry.getKey();
     UsageNode node = entry.getValue();
     if (node != null && node != NULL_NODE && !node.isExcluded() && usage.isReadOnly()) {
       result.add(usage);
     }
   }
   return result;
 }
Esempio n. 11
0
 private String generateOverviewText() throws InsufficientDataException {
   StringBuilder sb = new StringBuilder();
   final String team = config.getTeam();
   double total = checkTotal();
   final String nl = System.getProperty("line.separator");
   for (Entry<String, Row> entry : rows.entrySet()) {
     double hours = Double.parseDouble(entry.getValue().hoursTF.getText());
     double fraction = hours / total;
     if (fraction < 0.004) continue;
     String line = team + ", " + decimalFormat.format(fraction) + ", " + entry.getKey();
     sb.append(line + nl);
   }
   return sb.toString();
 }
  @Override
  public void dispose() {
    if (mySelectedEditor != null) {
      for (final Map.Entry<PropertiesFile, Editor> entry : myEditors.entrySet()) {
        if (mySelectedEditor.equals(entry.getValue())) {
          writeEditorPropertyValue(mySelectedEditor, entry.getKey(), null);
        }
      }
    }

    VirtualFileManager.getInstance().removeVirtualFileListener(myVfsListener);
    myDisposed = true;
    Disposer.dispose(myStructureViewComponent);
    releaseAllEditors();
  }
Esempio n. 13
0
 /**
  * \ Draw saved State (color dots on panel) on WhiteBoard
  *
  * @param outstream
  * @throws IOException
  */
 public void writeState(OutputStream outstream) throws IOException {
   if (state == null) return;
   synchronized (state) {
     DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(outstream));
     // DataOutputStream dos=new DataOutputStream(outstream);
     dos.writeInt(state.size());
     for (Map.Entry<Point, Color> entry : state.entrySet()) {
       Point point = entry.getKey();
       Color col = entry.getValue();
       dos.writeInt(point.x);
       dos.writeInt(point.x);
       dos.writeInt(col.getRGB());
     }
     dos.flush();
     System.out.println("wrote " + state.size() + " elements");
   }
 }
Esempio n. 14
0
 /** Draw the entire panel from the state */
 @SuppressWarnings("rawtypes")
 public void drawState() {
   // clear();
   Map.Entry entry;
   Point pt;
   Color col;
   synchronized (state) {
     for (Iterator it = state.entrySet().iterator(); it.hasNext(); ) {
       entry = (Map.Entry) it.next();
       pt = (Point) entry.getKey();
       col = (Color) entry.getValue();
       gr.setColor(col);
       gr.fillOval(pt.x, pt.y, 10, 10);
     }
   }
   repaint();
 }
  @Override
  @NotNull
  public Set<Usage> getExcludedUsages() {
    Set<Usage> result = new THashSet<Usage>();
    for (Map.Entry<Usage, UsageNode> entry : myUsageNodes.entrySet()) {
      UsageNode node = entry.getValue();
      Usage usage = entry.getKey();
      if (node == NULL_NODE || node == null) {
        continue;
      }
      if (node.isExcluded()) {
        result.add(usage);
      }
    }

    return result;
  }
Esempio n. 16
0
  /**
   * Makes a POST request and returns the server response.
   *
   * @param urlString the URL to post to
   * @param nameValuePairs a map of name/value pairs to supply in the request.
   * @return the server reply (either from the input stream or the error stream)
   */
  public static String doPost(String urlString, Map<String, String> nameValuePairs)
      throws IOException {
    URL url = new URL(urlString);
    URLConnection connection = url.openConnection();
    connection.setDoOutput(true);

    PrintWriter out = new PrintWriter(connection.getOutputStream());

    boolean first = true;
    for (Map.Entry<String, String> pair : nameValuePairs.entrySet()) {
      if (first) first = false;
      else out.print('&');
      String name = pair.getKey();
      String value = pair.getValue();
      out.print(name);
      out.print('=');
      out.print(URLEncoder.encode(value, "UTF-8"));
    }

    out.close();

    Scanner in;
    StringBuilder response = new StringBuilder();
    try {
      in = new Scanner(connection.getInputStream());
    } catch (IOException e) {
      if (!(connection instanceof HttpURLConnection)) throw e;
      InputStream err = ((HttpURLConnection) connection).getErrorStream();
      if (err == null) throw e;
      in = new Scanner(err);
    }

    while (in.hasNextLine()) {
      response.append(in.nextLine());
      response.append("\n");
    }

    in.close();
    return response.toString();
  }
 private void refreshLineMarkers() {
   for (Map.Entry<RangeMarker, LineMarkerInfo> entry : myLineMarkerInfos.entrySet()) {
     RangeMarker rangeMarker = entry.getKey();
     int startOffset = rangeMarker.getStartOffset();
     int endOffset = rangeMarker.getEndOffset();
     LineMarkerInfo value = entry.getValue();
     PsiElement element = value.getElement();
     assert element != null : value;
     TextRange range = new TextRange(startOffset, endOffset);
     final String tooltip = value.getLineMarkerTooltip();
     LineMarkerInfo markerInfo =
         new LineMarkerInfo<>(
             element,
             range,
             null,
             value.updatePass,
             e -> tooltip,
             null,
             GutterIconRenderer.Alignment.RIGHT);
     entry.setValue(markerInfo);
   }
 }
 private void refreshLineMarkers() {
   for (Map.Entry<RangeMarker, LineMarkerInfo> entry : lineMarkerInfos.entrySet()) {
     RangeMarker rangeMarker = entry.getKey();
     int startOffset = rangeMarker.getStartOffset();
     int endOffset = rangeMarker.getEndOffset();
     final LineMarkerInfo value = entry.getValue();
     LineMarkerInfo markerInfo =
         new LineMarkerInfo<PsiElement>(
             value.getElement(),
             new TextRange(startOffset, endOffset),
             null,
             value.updatePass,
             new Function<PsiElement, String>() {
               @Override
               public String fun(PsiElement psiElement) {
                 return value.getLineMarkerTooltip();
               }
             },
             null,
             GutterIconRenderer.Alignment.RIGHT);
     entry.setValue(markerInfo);
   }
 }
Esempio n. 19
0
    public TaskWrite(Map map1, Map m_max, Map m_min, DBCollection coll, ModbusSlaveSet slave) {

      try {
        synchronized (slave) {
          Calendar calener = Calendar.getInstance();
          Date d1 = calener.getTime();
          Date d2 = new Date(calener.getTime().getTime() - 5000);
          BasicDBObject b2 = new BasicDBObject();
          b2.put("$gte", d2);
          b2.put("$lte", d1);
          DBCursor cursor =
              coll.find(new BasicDBObject("_id", b2)).sort(new BasicDBObject("_id", -1)).limit(1);
          while (cursor.hasNext()) {
            DBObject dbo = cursor.next();
            Set set1 = map1.entrySet();
            Iterator it1 = set1.iterator();
            while (it1.hasNext()) {
              Map.Entry<String, Map<String, String>> entry =
                  (Map.Entry<String, Map<String, String>>) it1.next();
              Map<String, String> map2 = entry.getValue();
              for (Iterator it2 = map2.entrySet().iterator(); it2.hasNext(); ) {
                Map.Entry<String, String> entry2 = (Map.Entry<String, String>) it2.next();
                String name = entry2.getKey().toString();
                String paramAddr = entry2.getValue().toString();
                int fun = (int) (Double.parseDouble(paramAddr));
                if (paramAddr.substring(0, 1).equals("4")) {
                  double value = Double.parseDouble(dbo.get(name).toString());
                  double dmax = (Double) m_max.get(name);
                  double dmin = (Double) m_min.get(name);
                  double dValue = 0;
                  if (value > dmax || value < dmin) {
                    if (value >= 0) {
                      dValue = 32000 * (int) (value / dmax);
                    }
                    if (value < 0) {
                      dValue = -32000 * (int) (value / dmin);
                    }
                    // slave.getProcessImage(3).setInputRegister(fun % 10000, (short) dValue);
                  } else { /// 参数超限报警
                    JOptionPane.showMessageDialog(null, "参数超限");
                    slave.stop();
                  }
                }
                if (paramAddr.substring(0, 1).equals("3")) {
                  double value = Double.parseDouble(dbo.get(name).toString());
                  double dmax = (Double) m_max.get(name);
                  double dmin = (Double) m_min.get(name);
                  double dValue = 0;
                  if (value > dmax || value < dmin) {
                    if (value >= 0) {
                      dValue = 32000 * (int) (value / dmax);
                    }
                    if (value < 0) {
                      dValue = -32000 * (int) (value / dmin);
                    }
                    // slave.getProcessImage(3).setHoldingRegister(fun % 10000, (short) dValue);
                  } else { /// 参数超限报警
                    JOptionPane.showMessageDialog(null, "参数超限");
                    slave.stop();
                  }
                  ;
                }
                if (paramAddr.substring(0, 1).equals("2")) {
                  String value = dbo.get(name).toString();
                  /// slave.getProcessImage(4).setInput(fun % 10000, Boolean.valueOf(value));
                }
                if (paramAddr.substring(0, 1).equals("1")) {
                  String value = dbo.get(name).toString();
                  // slave.getProcessImage(4).setCoil(fun % 10000, Boolean.valueOf(value));
                }
              }
            }
          }
        }
      } catch (Exception ex) {
      }
    }
Esempio n. 20
0
    public TaskRead(Map map1, Map m_max, Map m_min, DBCollection coll, ModbusSlaveSet slave) {
      try {
        //// 此处只要点击开始就能保存数据
        /// 方案:利用数据源发送单个布尔型变量(1,0)交替,链接成功,先判断是否链接成功,然后在保存数据
        synchronized (slave) {
          Map map = new HashMap();
          Set set1 = map1.entrySet();
          Iterator it1 = set1.iterator();
          while (it1.hasNext()) {
            Map.Entry<String, Map<String, String>> entry =
                (Map.Entry<String, Map<String, String>>) it1.next();
            Map<String, String> map2 = entry.getValue();
            for (Iterator it2 = map2.entrySet().iterator(); it2.hasNext(); ) {
              Map.Entry<String, String> entry2 = (Map.Entry<String, String>) it2.next();
              String name = entry2.getKey().toString();
              String paramAddr = entry2.getValue().toString();
              int fun = (int) (Double.parseDouble(paramAddr));
              if (paramAddr.substring(0, 1).equals("4")) {
                Short d4 = slave.getProcessImage(1).getInputRegister(fun % 10000);
                double dmax = (Double) m_max.get(name);
                double dmin = (Double) m_min.get(name);
                double dValue = 0;
                if (d4 >= 0) {
                  dValue = dmax * d4 / 32000;
                } else {
                  dValue = dmin * d4 / (-32000);
                }
                map.put(name, dValue);
              }
              if (paramAddr.substring(0, 1).equals("3")) {
                Short d3 = slave.getProcessImage(1).getHoldingRegister(fun % 10000);
                double dmax = (Double) m_max.get(name);
                double dmin = (Double) m_min.get(name);
                double dValue = 0;

                if (d3 >= 0) {
                  dValue = dmax * d3 / 32000;
                } else {
                  dValue = dmin * d3 / (-32000);
                }
                map.put(name, dValue);
              }
              if (paramAddr.substring(0, 1).equals("2")) {
                map.put(name, slave.getProcessImage(2).getInput(fun % 10000));
              }
              if (paramAddr.substring(0, 1).equals("1")) {
                Boolean a = slave.getProcessImage(2).getCoil(fun % 10000 - 1);
                map.put(name, a);
              }
            }
          }

          Calendar calendar = Calendar.getInstance();
          Date dd = calendar.getTime();

          BasicDBObject doc = new BasicDBObject();
          doc.put("_id", dd);

          Set set = map.entrySet();
          Iterator it = set.iterator();
          while (it.hasNext()) {
            Map.Entry<String, String> entry1 = (Map.Entry<String, String>) it.next();
            doc.put(entry1.getKey(), entry1.getValue());
          }
          coll.insert(doc);
        }
      } catch (Exception ex) {
      }
    }
 @SuppressWarnings("unchecked")
 public void setAttributes(Map<AttributeKey, Object> map) {
   for (Map.Entry<AttributeKey, Object> entry : map.entrySet()) {
     setAttribute(entry.getKey(), entry.getValue());
   }
 }
  public static String composeText(
      final Map<String, ExpectedHighlightingSet> types,
      Collection<HighlightInfo> infos,
      String text) {
    // filter highlighting data and map each highlighting to a tag name
    List<Pair<String, HighlightInfo>> list =
        ContainerUtil.mapNotNull(
            infos,
            (NullableFunction<HighlightInfo, Pair<String, HighlightInfo>>)
                info -> {
                  for (Map.Entry<String, ExpectedHighlightingSet> entry : types.entrySet()) {
                    final ExpectedHighlightingSet set = entry.getValue();
                    if (set.enabled
                        && set.severity == info.getSeverity()
                        && set.endOfLine == info.isAfterEndOfLine()) {
                      return Pair.create(entry.getKey(), info);
                    }
                  }
                  return null;
                });

    boolean showAttributesKeys = false;
    for (ExpectedHighlightingSet eachSet : types.values()) {
      for (HighlightInfo eachInfo : eachSet.infos) {
        if (eachInfo.forcedTextAttributesKey != null) {
          showAttributesKeys = true;
          break;
        }
      }
    }

    // sort filtered highlighting data by end offset in descending order
    Collections.sort(
        list,
        (o1, o2) -> {
          HighlightInfo i1 = o1.second;
          HighlightInfo i2 = o2.second;

          int byEnds = i2.endOffset - i1.endOffset;
          if (byEnds != 0) return byEnds;

          if (!i1.isAfterEndOfLine() && !i2.isAfterEndOfLine()) {
            int byStarts = i1.startOffset - i2.startOffset;
            if (byStarts != 0) return byStarts;
          } else {
            int byEOL = Comparing.compare(i2.isAfterEndOfLine(), i1.isAfterEndOfLine());
            if (byEOL != 0) return byEOL;
          }

          int bySeverity = i2.getSeverity().compareTo(i1.getSeverity());
          if (bySeverity != 0) return bySeverity;

          return Comparing.compare(i1.getDescription(), i2.getDescription());
        });

    // combine highlighting data with original text
    StringBuilder sb = new StringBuilder();
    Couple<Integer> result = composeText(sb, list, 0, text, text.length(), 0, showAttributesKeys);
    sb.insert(0, text.substring(0, result.second));
    return sb.toString();
  }
  public void apply() throws ConfigurationException {
    // validate content and source roots
    final Map<VirtualFile, String> contentRootToModuleNameMap = new HashMap<VirtualFile, String>();
    final Map<VirtualFile, VirtualFile> srcRootsToContentRootMap =
        new HashMap<VirtualFile, VirtualFile>();
    for (final ModuleEditor moduleEditor : myModuleEditors.values()) {
      final ModifiableRootModel rootModel = moduleEditor.getModifiableRootModel();
      final ContentEntry[] contents = rootModel.getContentEntries();
      for (ContentEntry contentEntry : contents) {
        final VirtualFile contentRoot = contentEntry.getFile();
        if (contentRoot == null) {
          continue;
        }
        final String moduleName = moduleEditor.getName();
        final String previousName = contentRootToModuleNameMap.put(contentRoot, moduleName);
        if (previousName != null && !previousName.equals(moduleName)) {
          throw new ConfigurationException(
              ProjectBundle.message(
                  "module.paths.validation.duplicate.content.error",
                  contentRoot.getPresentableUrl(),
                  previousName,
                  moduleName));
        }
        for (VirtualFile srcRoot : contentEntry.getSourceFolderFiles()) {
          final VirtualFile anotherContentRoot = srcRootsToContentRootMap.put(srcRoot, contentRoot);
          if (anotherContentRoot != null) {
            final String problematicModule;
            final String correctModule;
            if (VfsUtilCore.isAncestor(anotherContentRoot, contentRoot, true)) {
              problematicModule = contentRootToModuleNameMap.get(anotherContentRoot);
              correctModule = contentRootToModuleNameMap.get(contentRoot);
            } else {
              problematicModule = contentRootToModuleNameMap.get(contentRoot);
              correctModule = contentRootToModuleNameMap.get(anotherContentRoot);
            }
            throw new ConfigurationException(
                ProjectBundle.message(
                    "module.paths.validation.duplicate.source.root.error",
                    problematicModule,
                    srcRoot.getPresentableUrl(),
                    correctModule));
          }
        }
      }
    }
    // additional validation: directories marked as src roots must belong to the same module as
    // their corresponding content root
    for (Map.Entry<VirtualFile, VirtualFile> entry : srcRootsToContentRootMap.entrySet()) {
      final VirtualFile srcRoot = entry.getKey();
      final VirtualFile correspondingContent = entry.getValue();
      final String expectedModuleName = contentRootToModuleNameMap.get(correspondingContent);

      for (VirtualFile candidateContent = srcRoot;
          candidateContent != null && !candidateContent.equals(correspondingContent);
          candidateContent = candidateContent.getParent()) {
        final String moduleName = contentRootToModuleNameMap.get(candidateContent);
        if (moduleName != null && !moduleName.equals(expectedModuleName)) {
          throw new ConfigurationException(
              ProjectBundle.message(
                  "module.paths.validation.source.root.belongs.to.another.module.error",
                  srcRoot.getPresentableUrl(),
                  expectedModuleName,
                  moduleName));
        }
      }
    }

    final List<ModifiableRootModel> models =
        new ArrayList<ModifiableRootModel>(myModuleEditors.size());
    for (ModuleEditor moduleEditor : myModuleEditors.values()) {
      moduleEditor.canApply();
    }

    final Map<Sdk, Sdk> modifiedToOriginalMap = new HashMap<Sdk, Sdk>();
    final ProjectSdksModel projectJdksModel =
        ProjectStructureConfigurable.getInstance(myProject).getProjectJdksModel();
    for (Map.Entry<Sdk, Sdk> entry : projectJdksModel.getProjectSdks().entrySet()) {
      modifiedToOriginalMap.put(entry.getValue(), entry.getKey());
    }

    final Ref<ConfigurationException> exceptionRef = Ref.create();
    DumbService.getInstance(myProject)
        .allowStartingDumbModeInside(
            DumbModePermission.MAY_START_BACKGROUND,
            new Runnable() {
              public void run() {
                ApplicationManager.getApplication()
                    .runWriteAction(
                        new Runnable() {
                          @Override
                          public void run() {
                            try {
                              for (final ModuleEditor moduleEditor : myModuleEditors.values()) {
                                final ModifiableRootModel model = moduleEditor.apply();
                                if (model != null) {
                                  if (!model.isSdkInherited()) {
                                    // make sure the sdk is set to original SDK stored in the JDK
                                    // Table
                                    final Sdk modelSdk = model.getSdk();
                                    if (modelSdk != null) {
                                      final Sdk original = modifiedToOriginalMap.get(modelSdk);
                                      if (original != null) {
                                        model.setSdk(original);
                                      }
                                    }
                                  }
                                  models.add(model);
                                }
                              }
                              myFacetsConfigurator.applyEditors();
                            } catch (ConfigurationException e) {
                              exceptionRef.set(e);
                              return;
                            }

                            try {
                              final ModifiableRootModel[] rootModels =
                                  models.toArray(new ModifiableRootModel[models.size()]);
                              ModifiableModelCommitter.multiCommit(rootModels, myModuleModel);
                              myModuleModelCommitted = true;
                              myFacetsConfigurator.commitFacets();

                            } finally {
                              ModuleStructureConfigurable.getInstance(myProject)
                                  .getFacetEditorFacade()
                                  .clearMaps(false);

                              myFacetsConfigurator = createFacetsConfigurator();
                              myModuleModel =
                                  ModuleManager.getInstance(myProject).getModifiableModel();
                              myModuleModelCommitted = false;
                            }
                          }
                        });
              }
            });

    if (!exceptionRef.isNull()) {
      throw exceptionRef.get();
    }

    myModified = false;
  }
Esempio n. 24
0
 public void reloadShortcuts() {
   for (Map.Entry<FPref, KeyboardShortcutField> e : shortcutFields.entrySet()) {
     e.getValue().reload(e.getKey());
   }
 }