/** * Compute a logical, reasonably efficient join on the specified tables. See project description * for hints on how this should be implemented. * * @param stats Statistics for each table involved in the join, referenced by base table names, * not alias * @param filterSelectivities Selectivities of the filter predicates on each table in the join, * referenced by table alias (if no alias, the base table name) * @param explain Indicates whether your code should explain its query plan or simply execute it * @return A Vector<LogicalJoinNode> that stores joins in the left-deep order in which they should * be executed. * @throws ParsingException when stats or filter selectivities is missing a table in the join, or * or when another internal error occurs */ public Vector<LogicalJoinNode> orderJoins( HashMap<String, TableStats> stats, HashMap<String, Double> filterSelectivities, boolean explain) throws ParsingException { // See the project writeup for some hints as to how this function // should work. // some code goes here PlanCache pc = new PlanCache(); for (int i = 1; i <= joins.size(); i++) { Set<Set<LogicalJoinNode>> subsets = enumerateSubsets(joins, i); for (Set<LogicalJoinNode> subset : subsets) { CostCard best = new CostCard(); best.cost = Double.MAX_VALUE; for (LogicalJoinNode node : subset) { CostCard subCard = computeCostAndCardOfSubplan(stats, filterSelectivities, node, subset, best.cost, pc); if (subCard != null) { if (subCard.cost < best.cost) best = subCard; pc.addPlan(subset, best.cost, best.card, best.plan); } } } } if (explain) printJoins(joins, pc, stats, filterSelectivities); HashSet<LogicalJoinNode> joinSet = new HashSet<LogicalJoinNode>(); for (int i = 0; i < joins.size(); i++) { joinSet.add(joins.get(i)); } Vector<LogicalJoinNode> order = pc.getOrder(joinSet); if (order != null) return order; return joins; }
private JPanel getClickableTagsPanel() { JPanel pnl = new JPanel(); pnl.setLayout(new GridLayout(0, 3)); ArrayList<Commontags> listTags = new ArrayList<>(mapAllTags.values()); Collections.sort(listTags); for (final Commontags ctag : listTags) { JCheckBox cb = new JCheckBox(ctag.getText()); cb.setForeground(GUITools.getColor(ctag.getColor())); cb.setFont(ctag.getType() == 0 ? SYSConst.ARIAL12 : SYSConst.ARIAL12BOLD); cb.setSelected(listSelectedTags.contains(ctag)); cb.addItemListener( e -> { if (e.getStateChange() == ItemEvent.SELECTED) { listSelectedTags.add(ctag); add(createButton(ctag)); } else { listSelectedTags.remove(ctag); mapButtons.remove(ctag); } notifyListeners(ctag); }); pnl.add(cb); } return pnl; }
private void handleBranchingInstruction( ProblemsHolder holder, StandardInstructionVisitor visitor, Set<Instruction> trueSet, Set<Instruction> falseSet, HashSet<PsiElement> reportedAnchors, BranchingInstruction instruction, final boolean onTheFly) { PsiElement psiAnchor = instruction.getPsiAnchor(); boolean underBinary = isAtRHSOfBooleanAnd(psiAnchor); if (instruction instanceof InstanceofInstruction && visitor.isInstanceofRedundant((InstanceofInstruction) instruction)) { if (visitor.canBeNull((BinopInstruction) instruction)) { holder.registerProblem( psiAnchor, InspectionsBundle.message("dataflow.message.redundant.instanceof"), new RedundantInstanceofFix()); } else { final LocalQuickFix localQuickFix = createSimplifyBooleanExpressionFix(psiAnchor, true); holder.registerProblem( psiAnchor, InspectionsBundle.message( underBinary ? "dataflow.message.constant.condition.when.reached" : "dataflow.message.constant.condition", Boolean.toString(true)), localQuickFix == null ? null : new LocalQuickFix[] {localQuickFix}); } } else if (psiAnchor instanceof PsiSwitchLabelStatement) { if (falseSet.contains(instruction)) { holder.registerProblem( psiAnchor, InspectionsBundle.message("dataflow.message.unreachable.switch.label")); } } else if (psiAnchor != null && !reportedAnchors.contains(psiAnchor) && !isFlagCheck(psiAnchor)) { boolean evaluatesToTrue = trueSet.contains(instruction); final PsiElement parent = psiAnchor.getParent(); if (parent instanceof PsiAssignmentExpression && ((PsiAssignmentExpression) parent).getLExpression() == psiAnchor) { holder.registerProblem( psiAnchor, InspectionsBundle.message( "dataflow.message.pointless.assignment.expression", Boolean.toString(evaluatesToTrue)), createConditionalAssignmentFixes( evaluatesToTrue, (PsiAssignmentExpression) parent, onTheFly)); } else if (!skipReportingConstantCondition(visitor, psiAnchor, evaluatesToTrue)) { final LocalQuickFix fix = createSimplifyBooleanExpressionFix(psiAnchor, evaluatesToTrue); String message = InspectionsBundle.message( underBinary ? "dataflow.message.constant.condition.when.reached" : "dataflow.message.constant.condition", Boolean.toString(evaluatesToTrue)); holder.registerProblem(psiAnchor, message, fix == null ? null : new LocalQuickFix[] {fix}); } reportedAnchors.add(psiAnchor); } }
/** @return String[] with all unique attributes on element level */ private String[] getAttributes() { HashSet<String> results = new HashSet(); for (ProcessInstance pi : mylog.getInstances()) { for (AuditTrailEntry ate : pi.getListOfATEs()) { results.addAll(ate.getAttributes().keySet()); } } String[] t = new String[results.size()]; return results.toArray(t); }
private Set<String> getLoadedPaths() { if (!IGV.hasInstance()) return new HashSet<String>(); Collection<ResourceLocator> locators = IGV.getInstance().getDataResourceLocators(); HashSet<String> loadedPaths = new HashSet<String>(locators.size()); for (ResourceLocator locator : locators) { loadedPaths.add(locator.getPath()); } return loadedPaths; }
private Collection getLayerManagers() { // Multiple windows may point to the same LayerManager, so use // a Set. [Jon Aquino] HashSet layerManagers = new HashSet(); JInternalFrame[] internalFrames = getInternalFrames(); for (int i = 0; i < internalFrames.length; i++) { if (internalFrames[i] instanceof LayerManagerProxy) { layerManagers.add(((LayerManagerProxy) internalFrames[i]).getLayerManager()); } } return layerManagers; }
/** * Prepare branches for the case of remote checkout * * @param remoteBranch the remote branch to checkout * @param roots the collection of vcs roots * @return the list of descriptors for the remote * @throws VcsException if failed */ private List<BranchDescriptor> prepareBranchesForRemote( String remoteBranch, List<VirtualFile> roots) throws VcsException { assert roots.size() > 0; List<BranchDescriptor> rc = new ArrayList<BranchDescriptor>(); HashSet<String> allBranches = new HashSet<String>(); allBranches.addAll(myConfig.getConfigurationNames()); final String qualifiedBranch = "remotes/" + remoteBranch; String firstRemote = remoteBranch.endsWith("/HEAD") ? null : qualifiedBranch; for (VirtualFile root : roots) { BranchDescriptor d = new BranchDescriptor(); d.root = root; d.currentReference = myConfig.describeRoot(root); if (firstRemote == null) { firstRemote = resolveHead(qualifiedBranch, d.root.getPath()); } d.referenceToCheckout = qualifiedBranch; Branch.listAsStrings(myProject, root, false, true, d.existingBranches, null); Branch.listAsStrings(myProject, root, true, true, d.referencesToSelect, null); allBranches.addAll(d.existingBranches); rc.add(d); } String candidate; if (firstRemote == null) { candidate = "untitled"; } else { int p = firstRemote.indexOf('/', REMOTES_PREFIX.length() + 1); assert p > 0 && p < firstRemote.length() - 1 : "Unexpected format for remote branch: " + firstRemote; candidate = firstRemote.substring(p + 1); } String actual = null; if (!allBranches.contains(candidate)) { actual = candidate; } else { for (int i = 2; i < Integer.MAX_VALUE; i++) { String t = candidate + i; if (!allBranches.contains(t)) { actual = t; break; } } assert actual != null : "Unexpected number of branches: " + remoteBranch; } for (BranchDescriptor d : rc) { d.newBranchName = actual; d.updateStatus(); } return rc; }
public InspectionTree(final Project project) { super(new InspectionRootNode(project)); setCellRenderer(new CellRenderer()); // project)); setShowsRootHandles(true); UIUtil.setLineStyleAngled(this); addTreeWillExpandListener(new ExpandListener()); myExpandedUserObjects = new HashSet<Object>(); myExpandedUserObjects.add(project); TreeUtil.installActions(this); new TreeSpeedSearch( this, new Convertor<TreePath, String>() { @Override public String convert(TreePath o) { return InspectionsConfigTreeComparator.getDisplayTextToSort( o.getLastPathComponent().toString()); } }); addTreeSelectionListener( new TreeSelectionListener() { @Override public void valueChanged(TreeSelectionEvent e) { TreePath newSelection = e.getNewLeadSelectionPath(); if (newSelection != null) { mySelectionPath = new SelectionPath(newSelection); } } }); }
@NotNull private static Set<String> resolveModuleDeps( @NotNull ModifiableRootModel rootModel, @NotNull ImportedOtpApp importedOtpApp, @Nullable Sdk projectSdk, @NotNull Set<String> allImportedAppNames) { HashSet<String> unresolvedAppNames = ContainerUtil.newHashSet(); for (String depAppName : importedOtpApp.getDeps()) { if (allImportedAppNames.contains(depAppName)) { rootModel.addInvalidModuleEntry(depAppName); } else if (projectSdk != null && isSdkOtpApp(depAppName, projectSdk)) { // SDK is already a dependency } else { rootModel.addInvalidModuleEntry(depAppName); unresolvedAppNames.add(depAppName); } } return unresolvedAppNames; }
/** Update state dialog depending on the current state of the fields */ private void updateDialogState() { String branch = myBranchTextField.getText(); if (branch.length() != 0) { setOKButtonText(GitBundle.getString("unstash.button.branch")); myPopStashCheckBox.setEnabled(false); myPopStashCheckBox.setSelected(true); myReinstateIndexCheckBox.setEnabled(false); myReinstateIndexCheckBox.setSelected(true); if (!GitBranchNameValidator.INSTANCE.checkInput(branch)) { setErrorText(GitBundle.getString("unstash.error.invalid.branch.name")); setOKActionEnabled(false); return; } if (myBranches.contains(branch)) { setErrorText(GitBundle.getString("unstash.error.branch.exists")); setOKActionEnabled(false); return; } } else { if (!myPopStashCheckBox.isEnabled()) { myPopStashCheckBox.setSelected(false); } myPopStashCheckBox.setEnabled(true); setOKButtonText( myPopStashCheckBox.isSelected() ? GitBundle.getString("unstash.button.pop") : GitBundle.getString("unstash.button.apply")); if (!myReinstateIndexCheckBox.isEnabled()) { myReinstateIndexCheckBox.setSelected(false); } myReinstateIndexCheckBox.setEnabled(true); } if (myStashList.getModel().getSize() == 0) { myViewButton.setEnabled(false); myDropButton.setEnabled(false); myClearButton.setEnabled(false); setErrorText(null); setOKActionEnabled(false); return; } else { myClearButton.setEnabled(true); } if (myStashList.getSelectedIndex() == -1) { myViewButton.setEnabled(false); myDropButton.setEnabled(false); setErrorText(null); setOKActionEnabled(false); return; } else { myViewButton.setEnabled(true); myDropButton.setEnabled(true); } setErrorText(null); setOKActionEnabled(true); }
protected void createOWLVizTabUI() { setLayout(new BorderLayout()); // Create the tabbed pane tabbedPane = new JTabbedPane(); add(tabbedPane); // ///////////////////////////////////////////////////////////////////// // // Build the asserted subclass hierarchy tabs // // //////////////////////////////////////////////////////////////////// assertedGraphModel = new OWLClassGraphAssertedModel(getOWLModelManager()); OWLVizGraphPanel assertedPanel = new OWLVizGraphPanel("Asserted hierarchy", this, getOWLEditorKit(), assertedGraphModel); assertedGraphComponent = assertedPanel.getGraphComponent(); setupListeners(assertedGraphComponent); tabbedPane.add(assertedPanel.getName(), assertedPanel); graphComponents.add(assertedGraphComponent); // ///////////////////////////////////////////////////////////////////// // // Build the inferred subclass hierarchy tabs // // //////////////////////////////////////////////////////////////////// inferredGraphModel = new OWLClassGraphInferredModel(getOWLModelManager()); OWLVizGraphPanel inferredPanel = new OWLVizGraphPanel("Inferred hierarchy", this, getOWLEditorKit(), inferredGraphModel); inferredGraphComponent = inferredPanel.getGraphComponent(); tabbedPane.add(inferredPanel.getName(), inferredPanel); graphComponents.add(inferredGraphComponent); // Group the asserted and inferred hierarchy tabs, so that operations // such as showing subclasses etc. are applied to both tabs. ArrayList<GraphComponent> list = new ArrayList<GraphComponent>(); list.add(assertedGraphComponent); list.add(inferredGraphComponent); componentGroupMap.put(assertedPanel, list); componentGroupMap.put(inferredPanel, list); // Create the toolbar createToolBar(assertedGraphComponent.getController(), assertedGraphComponent.getController()); }
public Profile(Element el) { name = el.getAttribute("name"); ids = new HashSet<String>(); Node child = el.getFirstChild(); while (child != null) { if (child.getNodeType() == Node.ELEMENT_NODE) { ids.add(((Element) child).getAttribute("id")); } child = child.getNextSibling(); } }
public void appendTo(Element el) { Document doc = el.getOwnerDocument(); Element p = doc.createElement("profile"); p.setAttribute("name", name); Iterator<String> it = ids.iterator(); while (it.hasNext()) { Element child = doc.createElement("enable"); child.setAttribute("id", it.next()); p.appendChild(child); } el.appendChild(p); }
private void restoreExpansionStatus(InspectionTreeNode node) { if (myExpandedUserObjects.contains(node.getUserObject())) { sortChildren(node); TreeNode[] pathToNode = node.getPath(); expandPath(new TreePath(pathToNode)); Enumeration children = node.children(); while (children.hasMoreElements()) { InspectionTreeNode childNode = (InspectionTreeNode) children.nextElement(); restoreExpansionStatus(childNode); } } }
private JButton createButton(final Commontags commontag) { if (mapButtons.containsKey(commontag)) { OPDE.debug("shortcut"); return mapButtons.get(commontag); } final JButton jButton = new JButton( commontag.getText(), editmode ? SYSConst.icon16tagPurpleDelete2 : SYSConst.icon16tagPurple); jButton.setFont(SYSConst.ARIAL12); jButton.setBorder(new RoundedBorder(10)); jButton.setHorizontalTextPosition(SwingConstants.LEADING); jButton.setForeground(SYSConst.purple1[SYSConst.dark3]); if (editmode) { jButton.addActionListener( e -> { listSelectedTags.remove(commontag); mapButtons.remove(commontag); SwingUtilities.invokeLater( () -> { removeAll(); add(txtTags); if (btnPickTags != null) { add(btnPickTags); } int tagnum = 1; for (JButton btn : mapButtons.values()) { if (tagnum % MAXLINE == 0) { add(btn, RiverLayout.LINE_BREAK); } else { add(btn, RiverLayout.LEFT); } tagnum++; } remove(jButton); revalidate(); repaint(); notifyListeners(commontag); }); }); } mapButtons.put(commontag, jButton); return jButton; }
/** * Get branch name status * * @param name the name to check * @return null if branch name is ok, or status describing the problem */ @Nullable private RootStatus branchNameStatus(final String name) { RootStatus b = null; if (!StringUtil.isEmpty(name)) { if (!BranchNameValidator.INSTANCE.checkInput(name)) { b = RootStatus.INVALID_BRANCH_NAME; } if (existingBranches.contains(name)) { b = RootStatus.BRANCH_NAME_EXISTS; } } return b; }
private void cmbTagsActionPerformed(ActionEvent e) { if (!editmode) return; if (txtTags.getText().isEmpty()) return; if (txtTags.getText().length() > 100) return; final String enteredText = SYSTools.tidy(txtTags.getText()).toLowerCase(); if (!addNewTags && !mapAllTags.containsKey(enteredText)) return; if (!mapAllTags.containsKey(enteredText)) { Commontags myNewCommontag = new Commontags(SYSTools.tidy(enteredText)); mapAllTags.put(enteredText, myNewCommontag); ac.uninstallListeners(); ac = new AutoCompletion(txtTags, mapAllTags.keySet().toArray(new String[] {})); ac.setStrict(false); ac.setStrictCompletion(false); } if (!listSelectedTags.contains(mapAllTags.get(enteredText))) { listSelectedTags.add(mapAllTags.get(enteredText)); SwingUtilities.invokeLater( () -> { if (listSelectedTags.size() % MAXLINE == 0) { add(createButton(mapAllTags.get(enteredText)), RiverLayout.LINE_BREAK); } else { add(createButton(mapAllTags.get(enteredText)), RiverLayout.LEFT); } txtTags.setText(""); revalidate(); repaint(); notifyListeners(mapAllTags.get(enteredText)); }); } }
/** * No-arg constructor. Initializes randomListOfPoints and listOfPointsToBeConnected. For * initialization of the randomListOfPoints is using HashSet<MyPoint> randomSetOfPoints, so we can * be sure, that there won't be equal points. randomListOfPoints will store from 30 to 50 unique * random points with coordinates in range of 100<=X<=700 and 100<=Y<=500. */ PointsConnector() { random = new Random(); listOfPointsToBeConnected = new ArrayList<MyPoint>(); HashSet<MyPoint> randomSetOfPoints = new HashSet<MyPoint>(); int initialCapacity = random.nextInt(21) + 30; int x, y; while (randomSetOfPoints.size() != initialCapacity) { x = random.nextInt(601) + 100; y = random.nextInt(401) + 100; randomSetOfPoints.add(new MyPoint(x, y)); } randomListOfPoints = new ArrayList<MyPoint>(randomSetOfPoints); Collections.sort( randomListOfPoints, new YcoordSorterComparator()); // sorting randomListOfPoints by Y. System.out.println("Sorted by Y input list of points:\n" + randomListOfPoints); }
/* * Track focus changes and update the current focus component * for the current tab */ public void propertyChange(PropertyChangeEvent e) { // No need to track focus change if (exceptions == null && focusPolicy == RESET_FOCUS) return; // Check for exceptions to the focus policy exist Component key = tabbedPane.getComponentAt(tabbedPane.getSelectedIndex()); if (exceptions != null) { if (focusPolicy == RESET_FOCUS && !exceptions.contains(key)) return; if (focusPolicy == RETAIN_FOCUS && exceptions.contains(key)) return; } // Track focus changes for the tab Component value = (Component) e.getNewValue(); if (value != null && SwingUtilities.isDescendingFrom(value, key)) { tabFocus.put(key, value); } }
/** Refresh stash list */ private void refreshStashList() { final DefaultListModel listModel = (DefaultListModel) myStashList.getModel(); listModel.clear(); GitStashUtils.loadStashStack( myProject, getGitRoot(), new Consumer<StashInfo>() { @Override public void consume(StashInfo stashInfo) { listModel.addElement(stashInfo); } }); myBranches.clear(); try { GitBranch.listAsStrings(myProject, getGitRoot(), false, true, myBranches, null); } catch (VcsException e) { // ignore error } myStashList.setSelectedIndex(0); }
private static ArrayList<CardDownloadData> getNeededCards(List<CardInfo> allCards) { ArrayList<CardDownloadData> cardsToDownload = new ArrayList<>(); /** read all card names and urls */ ArrayList<CardDownloadData> allCardsUrls = new ArrayList<>(); HashSet<String> ignoreUrls = SettingsManager.getIntance().getIgnoreUrls(); /** get filter for Standard Type 2 cards */ Set<String> type2SetsFilter = new HashSet<String>(); type2SetsFilter.addAll(ConstructedFormats.getSetsByFormat(ConstructedFormats.STANDARD)); try { offlineMode = true; for (CardInfo card : allCards) { if (card.getCardNumber() > 0 && !card.getSetCode().isEmpty() && !ignoreUrls.contains(card.getSetCode())) { String cardName = card.getName(); CardDownloadData url = new CardDownloadData( cardName, card.getSetCode(), card.getCardNumber(), card.usesVariousArt(), 0, "", false, card.isDoubleFaced(), card.isNightCard()); if (url.getUsesVariousArt()) { url.setDownloadName(createDownloadName(card)); } url.setFlipCard(card.isFlipCard()); url.setSplitCard(card.isSplitCard()); if (type2SetsFilter.contains(card.getSetCode())) { url.setType2(true); } allCardsUrls.add(url); if (card.isDoubleFaced()) { if (card.getSecondSideName() == null || card.getSecondSideName().trim().isEmpty()) { throw new IllegalStateException("Second side card can't have empty name."); } url = new CardDownloadData( card.getSecondSideName(), card.getSetCode(), card.getCardNumber(), card.usesVariousArt(), 0, "", false, card.isDoubleFaced(), true); allCardsUrls.add(url); } if (card.isFlipCard()) { if (card.getFlipCardName() == null || card.getFlipCardName().trim().isEmpty()) { throw new IllegalStateException("Flipped card can't have empty name."); } url = new CardDownloadData( card.getFlipCardName(), card.getSetCode(), card.getCardNumber(), card.usesVariousArt(), 0, "", false, card.isDoubleFaced(), card.isNightCard()); url.setFlipCard(true); url.setFlippedSide(true); allCardsUrls.add(url); } } else { if (card.getCardNumber() < 1) { System.err.println("There was a critical error!"); log.error("Card has no collector ID and won't be sent to client: " + card); } else if (card.getSetCode().isEmpty()) { System.err.println("There was a critical error!"); log.error("Card has no set name and won't be sent to client:" + card); } } } allCardsUrls.addAll(getTokenCardUrls()); } catch (Exception e) { log.error(e); } TFile file; /** check to see which cards we already have */ for (CardDownloadData card : allCardsUrls) { file = new TFile(CardImageUtils.generateImagePath(card)); if (!file.exists()) { cardsToDownload.add(card); } } for (CardDownloadData card : cardsToDownload) { if (card.isToken()) { log.info("Card to download: " + card.getName() + " (Token) "); } else { try { log.info("Card to download: " + card.getName() + " (" + card.getSet() + ")"); } catch (Exception e) { log.error(e); } } } return cardsToDownload; }
private void createDescription( StandardDataFlowRunner runner, ProblemsHolder holder, DataFlowInstructionVisitor visitor) { Pair<Set<Instruction>, Set<Instruction>> constConditions = runner.getConstConditionalExpressions(); Set<Instruction> trueSet = constConditions.getFirst(); Set<Instruction> falseSet = constConditions.getSecond(); ArrayList<Instruction> allProblems = new ArrayList<Instruction>(); allProblems.addAll(trueSet); allProblems.addAll(falseSet); allProblems.addAll(runner.getCCEInstructions()); allProblems.addAll(StandardDataFlowRunner.getRedundantInstanceofs(runner, visitor)); HashSet<PsiElement> reportedAnchors = new HashSet<PsiElement>(); for (PsiElement element : visitor.getProblems(NullabilityProblem.callNPE)) { if (reportedAnchors.add(element)) { reportCallMayProduceNpe(holder, (PsiMethodCallExpression) element, holder.isOnTheFly()); } } for (PsiElement element : visitor.getProblems(NullabilityProblem.fieldAccessNPE)) { if (reportedAnchors.add(element)) { PsiElement parent = element.getParent(); PsiElement fieldAccess = parent instanceof PsiArrayAccessExpression || parent instanceof PsiReferenceExpression ? parent : element; reportFieldAccessMayProduceNpe(holder, element, (PsiExpression) fieldAccess); } } for (Instruction instruction : allProblems) { if (instruction instanceof TypeCastInstruction && reportedAnchors.add( ((TypeCastInstruction) instruction).getCastExpression().getCastType())) { reportCastMayFail(holder, (TypeCastInstruction) instruction); } else if (instruction instanceof BranchingInstruction) { handleBranchingInstruction( holder, visitor, trueSet, falseSet, reportedAnchors, (BranchingInstruction) instruction); } } reportNullableArguments(visitor, holder, reportedAnchors); reportNullableAssignments(visitor, holder, reportedAnchors); reportUnboxedNullables(visitor, holder, reportedAnchors); if (!runner.isInNullableMethod() && runner.isInMethod() && (runner.isInNotNullMethod() || SUGGEST_NULLABLE_ANNOTATIONS)) { reportNullableReturns(runner, visitor, holder, reportedAnchors); } if (SUGGEST_NULLABLE_ANNOTATIONS) { reportNullableArgumentsPassedToNonAnnotated(visitor, holder, reportedAnchors); } if (REPORT_CONSTANT_REFERENCE_VALUES) { reportConstantReferenceValues(holder, visitor, reportedAnchors); } }
@Override public void run() { this.cardIndex = 0; File base = new File(Constants.IO.imageBaseDir); if (!base.exists()) { base.mkdir(); } Connection.ProxyType configProxyType = Connection.ProxyType.valueByText( PreferencesDialog.getCachedValue(PreferencesDialog.KEY_PROXY_TYPE, "None")); Proxy.Type type = Proxy.Type.DIRECT; switch (configProxyType) { case HTTP: type = Proxy.Type.HTTP; break; case SOCKS: type = Proxy.Type.SOCKS; break; case NONE: default: p = Proxy.NO_PROXY; break; } if (type != Proxy.Type.DIRECT) { try { String address = PreferencesDialog.getCachedValue(PreferencesDialog.KEY_PROXY_ADDRESS, ""); Integer port = Integer.parseInt( PreferencesDialog.getCachedValue(PreferencesDialog.KEY_PROXY_PORT, "80")); p = new Proxy(type, new InetSocketAddress(address, port)); } catch (Exception ex) { throw new RuntimeException("Gui_DownloadPictures : error 1 - " + ex); } } if (p != null) { HashSet<String> ignoreUrls = SettingsManager.getIntance().getIgnoreUrls(); ArrayList<CardDownloadData> cardsToDownload = this.checkBox.isSelected() ? type2cards : cards; update(0, cardsToDownload.size()); for (int i = 0; i < cardsToDownload.size() && !cancel; i++) { try { CardDownloadData card = cardsToDownload.get(i); log.info("Downloading card: " + card.getName() + " (" + card.getSet() + ")"); String url; if (ignoreUrls.contains(card.getSet()) || card.isToken()) { if (card.getCollectorId() != 0) { continue; } url = cardImageSource.generateTokenUrl(card); } else { url = cardImageSource.generateURL(card); } if (url != null) { Logger.getLogger(this.getClass()).info(url); Runnable task = new DownloadTask(card, new URL(url), cardsToDownload.size()); executor.execute(task); } else { synchronized (sync) { update(cardIndex + 1, cardsToDownload.size()); } } } catch (Exception ex) { log.error(ex, ex); } } executor.shutdown(); while (!executor.isTerminated()) { try { Thread.sleep(1000); } catch (InterruptedException ie) { } } } try { TVFS.umount(); } catch (FsSyncException e) { e.printStackTrace(); JOptionPane.showMessageDialog( null, "Couldn't unmount zip files", "Error", JOptionPane.ERROR_MESSAGE); } finally { System.gc(); } closeButton.setText("Close"); }
/** * Analyze class fields and fill in "voSetterMethods","voGetterMethods","indexes",reverseIndexes" * attributes. * * @param prefix e.g. "attrx.attry." * @param parentMethods getter methods of parent v.o. * @param classType class to analyze */ private void analyzeClassFields(String prefix, Method[] parentMethods, Class classType) { try { if (prefix.split("\\.").length > ClientSettings.MAX_NR_OF_LOOPS_IN_ANALYZE_VO) return; // retrieve all getter and setter methods defined in the specified value object... String attributeName = null; Method[] methods = classType.getMethods(); String aName = null; for (int i = 0; i < methods.length; i++) { attributeName = methods[i].getName(); if (attributeName.startsWith("get") && methods[i].getParameterTypes().length == 0 && ValueObject.class.isAssignableFrom(methods[i].getReturnType())) { aName = getAttributeName(attributeName, classType); Method[] newparentMethods = new Method[parentMethods.length + 1]; System.arraycopy(parentMethods, 0, newparentMethods, 0, parentMethods.length); newparentMethods[parentMethods.length] = methods[i]; analyzeClassFields(prefix + aName + ".", newparentMethods, methods[i].getReturnType()); } if (attributeName.startsWith("get") && methods[i].getParameterTypes().length == 0 && (methods[i].getReturnType().equals(String.class) || methods[i].getReturnType().equals(Long.class) || methods[i].getReturnType().equals(Long.TYPE) || methods[i].getReturnType().equals(Float.class) || methods[i].getReturnType().equals(Float.TYPE) || methods[i].getReturnType().equals(Short.class) || methods[i].getReturnType().equals(Short.TYPE) || methods[i].getReturnType().equals(Double.class) || methods[i].getReturnType().equals(Double.TYPE) || methods[i].getReturnType().equals(BigDecimal.class) || methods[i].getReturnType().equals(java.util.Date.class) || methods[i].getReturnType().equals(java.sql.Date.class) || methods[i].getReturnType().equals(java.sql.Timestamp.class) || methods[i].getReturnType().equals(Integer.class) || methods[i].getReturnType().equals(Integer.TYPE) || methods[i].getReturnType().equals(Character.class) || methods[i].getReturnType().equals(Boolean.class) || methods[i].getReturnType().equals(boolean.class) || methods[i].getReturnType().equals(ImageIcon.class) || methods[i].getReturnType().equals(Icon.class) || methods[i].getReturnType().equals(byte[].class) || methods[i].getReturnType().equals(Object.class) || ValueObject.class.isAssignableFrom(methods[i].getReturnType()))) { attributeName = getAttributeName(attributeName, classType); // try { // if // (classType.getMethod("set"+attributeName.substring(0,1).toUpperCase()+attributeName.substring(1),new Class[]{methods[i].getReturnType()})!=null) Method[] newparentMethods = new Method[parentMethods.length + 1]; System.arraycopy(parentMethods, 0, newparentMethods, 0, parentMethods.length); newparentMethods[parentMethods.length] = methods[i]; voGetterMethods.put(prefix + attributeName, newparentMethods); // } catch (NoSuchMethodException ex) { // } } else if (attributeName.startsWith("is") && methods[i].getParameterTypes().length == 0 && (methods[i].getReturnType().equals(Boolean.class) || methods[i].getReturnType().equals(boolean.class))) { attributeName = getAttributeName(attributeName, classType); Method[] newparentMethods = new Method[parentMethods.length + 1]; System.arraycopy(parentMethods, 0, newparentMethods, 0, parentMethods.length); newparentMethods[parentMethods.length] = methods[i]; voGetterMethods.put(prefix + attributeName, newparentMethods); } else if (attributeName.startsWith("set") && methods[i].getParameterTypes().length == 1) { attributeName = getAttributeName(attributeName, classType); try { if (classType.getMethod( "get" + attributeName.substring(0, 1).toUpperCase() + attributeName.substring(1), new Class[0]) != null) { Method[] newparentMethods = new Method[parentMethods.length + 1]; System.arraycopy(parentMethods, 0, newparentMethods, 0, parentMethods.length); newparentMethods[parentMethods.length] = methods[i]; voSetterMethods.put(prefix + attributeName, newparentMethods); } } catch (NoSuchMethodException ex) { try { if (classType.getMethod( "is" + attributeName.substring(0, 1).toUpperCase() + attributeName.substring(1), new Class[0]) != null) { Method[] newparentMethods = new Method[parentMethods.length + 1]; System.arraycopy(parentMethods, 0, newparentMethods, 0, parentMethods.length); newparentMethods[parentMethods.length] = methods[i]; voSetterMethods.put(prefix + attributeName, newparentMethods); } } catch (NoSuchMethodException exx) { } } } } // fill in indexes with the colProperties indexes first; after them, it will be added the // other indexes (of attributes not mapped with grid column...) HashSet alreadyAdded = new HashSet(); int i = 0; for (i = 0; i < colProperties.length; i++) { indexes.put(new Integer(i), colProperties[i].getColumnName()); reverseIndexes.put(colProperties[i].getColumnName(), new Integer(i)); alreadyAdded.add(colProperties[i].getColumnName()); } Enumeration en = voGetterMethods.keys(); while (en.hasMoreElements()) { attributeName = en.nextElement().toString(); if (!alreadyAdded.contains(attributeName)) { indexes.put(new Integer(i), attributeName); reverseIndexes.put(attributeName, new Integer(i)); i++; } } } catch (Exception ex) { ex.printStackTrace(); } }
/* * Specify a tab with an exception to the focus policy rule */ public void addException(int index) { if (exceptions == null) exceptions = new HashSet<Component>(); Component key = tabbedPane.getComponentAt(index); exceptions.add(key); }
public boolean has(String id) { return ids.contains(id); }
public void add(String id) { ids.add(id); }
/** * Helper function to display a Swing window with a tree representation of the specified list of * joins. See {@link #orderJoins}, which may want to call this when the analyze flag is true. * * @param js the join plan to visualize * @param pc the PlanCache accumulated whild building the optimal plan * @param stats table statistics for base tables * @param selectivities the selectivities of the filters over each of the tables (where tables are * indentified by their alias or name if no alias is given) */ private void printJoins( Vector<LogicalJoinNode> js, PlanCache pc, HashMap<String, TableStats> stats, HashMap<String, Double> selectivities) { JFrame f = new JFrame("Join Plan for " + p.getQuery()); // Set the default close operation for the window, // or else the program won't exit when clicking close button f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); f.setVisible(true); f.setSize(300, 500); HashMap<String, DefaultMutableTreeNode> m = new HashMap<String, DefaultMutableTreeNode>(); // int numTabs = 0; // int k; DefaultMutableTreeNode root = null, treetop = null; HashSet<LogicalJoinNode> pathSoFar = new HashSet<LogicalJoinNode>(); boolean neither; System.out.println(js); for (LogicalJoinNode j : js) { pathSoFar.add(j); System.out.println("PATH SO FAR = " + pathSoFar); String table1Name = Database.getCatalog().getTableName(this.p.getTableId(j.t1Alias)); String table2Name = Database.getCatalog().getTableName(this.p.getTableId(j.t2Alias)); // Double c = pc.getCost(pathSoFar); neither = true; root = new DefaultMutableTreeNode( "Join " + j + " (Cost =" + pc.getCost(pathSoFar) + ", card = " + pc.getCard(pathSoFar) + ")"); DefaultMutableTreeNode n = m.get(j.t1Alias); if (n == null) { // never seen this table before n = new DefaultMutableTreeNode( j.t1Alias + " (Cost = " + stats.get(table1Name).estimateScanCost() + ", card = " + stats.get(table1Name).estimateTableCardinality(selectivities.get(j.t1Alias)) + ")"); root.add(n); } else { // make left child root n root.add(n); neither = false; } m.put(j.t1Alias, root); n = m.get(j.t2Alias); if (n == null) { // never seen this table before n = new DefaultMutableTreeNode( j.t2Alias == null ? "Subplan" : (j.t2Alias + " (Cost = " + stats.get(table2Name).estimateScanCost() + ", card = " + stats .get(table2Name) .estimateTableCardinality(selectivities.get(j.t2Alias)) + ")")); root.add(n); } else { // make right child root n root.add(n); neither = false; } m.put(j.t2Alias, root); // unless this table doesn't join with other tables, // all tables are accessed from root if (!neither) { for (String key : m.keySet()) { m.put(key, root); } } treetop = root; } JTree tree = new JTree(treetop); JScrollPane treeView = new JScrollPane(tree); tree.setShowsRootHandles(true); // Set the icon for leaf nodes. ImageIcon leafIcon = new ImageIcon("join.jpg"); DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer(); renderer.setOpenIcon(leafIcon); renderer.setClosedIcon(leafIcon); tree.setCellRenderer(renderer); f.setSize(300, 500); f.add(treeView); for (int i = 0; i < tree.getRowCount(); i++) { tree.expandRow(i); } if (js.size() == 0) { f.add(new JLabel("No joins in plan.")); } f.pack(); }
/** * Preform a merge commit * * @param project a project * @param root a vcs root * @param added added files * @param removed removed files * @param messageFile a message file for commit * @param author an author * @param exceptions the list of exceptions to report * @param partialOperation * @return true if merge commit was successful */ private static boolean mergeCommit( final Project project, final VirtualFile root, final Set<FilePath> added, final Set<FilePath> removed, final File messageFile, final String author, List<VcsException> exceptions, @NotNull final PartialOperation partialOperation) { HashSet<FilePath> realAdded = new HashSet<FilePath>(); HashSet<FilePath> realRemoved = new HashSet<FilePath>(); // perform diff GitSimpleHandler diff = new GitSimpleHandler(project, root, GitCommand.DIFF); diff.setSilent(true); diff.setStdoutSuppressed(true); diff.addParameters("--diff-filter=ADMRUX", "--name-status", "HEAD"); diff.endOptions(); String output; try { output = diff.run(); } catch (VcsException ex) { exceptions.add(ex); return false; } String rootPath = root.getPath(); for (StringTokenizer lines = new StringTokenizer(output, "\n", false); lines.hasMoreTokens(); ) { String line = lines.nextToken().trim(); if (line.length() == 0) { continue; } String[] tk = line.split("\t"); switch (tk[0].charAt(0)) { case 'M': case 'A': realAdded.add(VcsUtil.getFilePath(rootPath + "/" + tk[1])); break; case 'D': realRemoved.add(VcsUtil.getFilePathForDeletedFile(rootPath + "/" + tk[1], false)); break; default: throw new IllegalStateException("Unexpected status: " + line); } } realAdded.removeAll(added); realRemoved.removeAll(removed); if (realAdded.size() != 0 || realRemoved.size() != 0) { final List<FilePath> files = new ArrayList<FilePath>(); files.addAll(realAdded); files.addAll(realRemoved); final Ref<Boolean> mergeAll = new Ref<Boolean>(); try { GuiUtils.runOrInvokeAndWait( new Runnable() { public void run() { String message = GitBundle.message("commit.partial.merge.message", partialOperation.getName()); SelectFilePathsDialog dialog = new SelectFilePathsDialog( project, files, message, null, "Commit All Files", CommonBundle.getCancelButtonText(), false); dialog.setTitle(GitBundle.getString("commit.partial.merge.title")); dialog.show(); mergeAll.set(dialog.isOK()); } }); } catch (RuntimeException ex) { throw ex; } catch (Exception ex) { throw new RuntimeException("Unable to invoke a message box on AWT thread", ex); } if (!mergeAll.get()) { return false; } // update non-indexed files if (!updateIndex(project, root, realAdded, realRemoved, exceptions)) { return false; } for (FilePath f : realAdded) { VcsDirtyScopeManager.getInstance(project).fileDirty(f); } for (FilePath f : realRemoved) { VcsDirtyScopeManager.getInstance(project).fileDirty(f); } } // perform merge commit try { GitSimpleHandler handler = new GitSimpleHandler(project, root, GitCommand.COMMIT); handler.setStdoutSuppressed(false); handler.addParameters("-F", messageFile.getAbsolutePath()); if (author != null) { handler.addParameters("--author=" + author); } handler.endOptions(); handler.run(); GitRepositoryManager manager = GitUtil.getRepositoryManager(project); manager.updateRepository(root); } catch (VcsException ex) { exceptions.add(ex); return false; } return true; }