/** * 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(); }
@Nullable public InstanceFactory findInstanceFactory(@Nonnull Type mockedType) { InstanceFactory instanceFactory = mockedTypesAndInstances.get(mockedType); if (instanceFactory != null) { return instanceFactory; } Class<?> mockedClass = getClassType(mockedType); //noinspection ReuseOfLocalVariable instanceFactory = mockedTypesAndInstances.get(mockedClass); if (instanceFactory != null) { return instanceFactory; } boolean abstractType = mockedClass.isInterface() || isAbstract(mockedClass.getModifiers()); for (Entry<Type, InstanceFactory> entry : mockedTypesAndInstances.entrySet()) { Type registeredMockedType = entry.getKey(); Class<?> registeredMockedClass = getClassType(registeredMockedType); if (abstractType) { registeredMockedClass = getMockedClassOrInterfaceType(registeredMockedClass); } if (mockedClass.isAssignableFrom(registeredMockedClass)) { instanceFactory = entry.getValue(); break; } } return instanceFactory; }
boolean isEquivalentInstance( @Nonnull Object invocationInstance, @Nonnull Object invokedInstance) { return invocationInstance == invokedInstance || invocationInstance == replacementMap.get(invokedInstance) || invocationInstance == instanceMap.get(invokedInstance) || invokedInstance == instanceMap.get(invocationInstance) || TestRun.getExecutingTest() .isInvokedInstanceEquivalentToCapturedInstance(invocationInstance, invokedInstance); }
private void restoreAndRemoveTransformedClasses( @Nonnull Set<ClassIdentification> classesToRestore) { RedefinitionEngine redefinitionEngine = new RedefinitionEngine(); for (ClassIdentification transformedClassId : classesToRestore) { byte[] definitionToRestore = transformedClasses.get(transformedClassId); redefinitionEngine.restoreToDefinition( transformedClassId.getLoadedClass(), definitionToRestore); } transformedClasses.keySet().removeAll(classesToRestore); }
void removeMockedClasses(@Nonnull List<Class<?>> previousMockedClasses) { int currentMockedClassCount = mockedClasses.size(); if (currentMockedClassCount > 0) { int previousMockedClassCount = previousMockedClasses.size(); if (previousMockedClassCount == 0) { mockedClasses.clear(); mockedTypesAndInstances.clear(); } else if (previousMockedClassCount < currentMockedClassCount) { mockedClasses.retainAll(previousMockedClasses); mockedTypesAndInstances.keySet().retainAll(previousMockedClasses); } } }
void restoreRedefinedClasses(@Nonnull Map<?, byte[]> previousDefinitions) { if (redefinedClasses.isEmpty()) { return; } RedefinitionEngine redefinitionEngine = new RedefinitionEngine(); Iterator<Entry<Class<?>, byte[]>> itr = redefinedClasses.entrySet().iterator(); while (itr.hasNext()) { Entry<Class<?>, byte[]> entry = itr.next(); Class<?> redefinedClass = entry.getKey(); byte[] currentDefinition = entry.getValue(); byte[] previousDefinition = previousDefinitions.get(redefinedClass); //noinspection ArrayEquality if (currentDefinition != previousDefinition) { redefinitionEngine.restoreDefinition(redefinedClass, previousDefinition); if (previousDefinition == null) { restoreDefinition(redefinedClass); discardStateForCorrespondingMockClassIfAny(redefinedClass); itr.remove(); } else { entry.setValue(previousDefinition); } } } }
void restoreTransformedClasses(@Nonnull Set<ClassIdentification> previousTransformedClasses) { if (!transformedClasses.isEmpty()) { Set<ClassIdentification> classesToRestore; if (previousTransformedClasses.isEmpty()) { classesToRestore = transformedClasses.keySet(); } else { classesToRestore = getTransformedClasses(); classesToRestore.removeAll(previousTransformedClasses); } if (!classesToRestore.isEmpty()) { restoreAndRemoveTransformedClasses(classesToRestore); } } }
private void registerReplacementInstanceIfApplicable( @Nullable Object mock, @Nonnull ExpectedInvocation invocation) { Object replacementInstance = invocation.replacementInstance; if (replacementInstance != null && replacementInstance != invocation.instance) { replacementMap.put(mock, replacementInstance); } }
/** * Adds a single row to the {@link #reviewPanel}. * * @param gbl The layout to add the row to. * @param gbc The layout constraints to use. * @param title The title of the top-level project. * @param hours The amount of hours spent on the project. */ private void addRow(GridBagLayout gbl, GridBagConstraints gbc, String title, double hours) { Row row = new Row(); addLeftLabel(gbl, gbc, title); addMiddleField(gbl, gbc, row, hours); addRightLabel(gbl, gbc); addPercentLabel(gbl, gbc, row); rows.put(title, row); gbc.gridy++; }
boolean areInDifferentEquivalenceSets(@Nonnull Object mock1, @Nonnull Object mock2) { if (mock1 == mock2 || instanceMap.isEmpty()) { return false; } Object mock1Equivalent = instanceMap.get(mock1); Object mock2Equivalent = instanceMap.get(mock2); if (mock1Equivalent == mock2 || mock2Equivalent == mock1) { return false; } if (mock1Equivalent != null && mock2Equivalent != null) { return true; } return instanceMapHasMocksInSeparateEntries(mock1, mock2); }
/** * Generates a string representation of the configuration options. * * @return A string * @see java.lang.Object#toString() */ public String toString() { StringBuilder buff = new StringBuilder("AjaxMetricsFilterConfiguration:"); buff.append("\n\tParameter Names:"); for (Entry<String, String> entry : parameterNames.entrySet()) { buff.append("\n\t\t").append(entry.getKey()).append(":").append(entry.getValue()); } buff.append("\n\tRun Options:"); for (Entry<String, Boolean> entry : runOptions.entrySet()) { buff.append("\n\t\t").append(entry.getKey()).append(":").append(entry.getValue()); } buff.append("\n\tBatch Options:"); for (Entry<String, Integer> entry : batchOptions.entrySet()) { buff.append("\n\t\t").append(entry.getKey()).append(":").append(entry.getValue()); } buff.append("\n\tListener Class Name:").append(listenerClassName); buff.append("\n\tAgent Logging Level:").append(agentLogLevel); buff.append("\n\tAgent Name:").append(agentName); return buff.toString(); }
public boolean isStillMocked(@Nullable Object instance, @Nonnull String classDesc) { Class<?> targetClass; if (instance == null) { targetClass = ClassLoad.loadByInternalName(classDesc); return isClassAssignableTo(mockedClasses, targetClass); } targetClass = instance.getClass(); return mockedTypesAndInstances.containsKey(targetClass) || isInstanceOfMockedClass(instance); }
/** * Get the vertex with the maximal label. * * @param vertexLabels Map that gives a label for each vertex. * @return Vertex with the maximal label. */ private V getMaxLabelVertex(Map<V, Integer> vertexLabels) { Iterator<Entry<V, Integer>> iterator = vertexLabels.entrySet().iterator(); Entry<V, Integer> max = iterator.next(); while (iterator.hasNext()) { Entry<V, Integer> e = iterator.next(); if (e.getValue() > max.getValue()) { max = e; } } return max.getKey(); }
/** * This function re-computes the total number of hours for the selected period. It is ran every * time the user edits a text field specifying the number of hours for a particular top-level * project. Percentage labels are also updated. */ private void recomputeTotal() { double total = 0; for (Row row : rows.values()) { try { row.hours = Double.parseDouble(row.hoursTF.getText()); total += row.hours; row.hoursTF.setForeground(normalColour); } catch (NumberFormatException e) { row.hoursTF.setForeground(errorColour); totalLabel.setText("ERROR"); totalLabel.setForeground(errorColour); return; } } totalLabel.setText(decimalFormat.format(total)); totalLabel.setForeground(normalColour); for (Row row : rows.values()) { String percentS = decimalFormat.format(total == 0 ? 0 : 100 * row.hours / total); row.percentL.setText("(" + percentS + "%)"); } pack(); }
/** * Generates a JavaScript command to update the JavaScript agent's parameter names. Follows this * format: <code>agent.updateParameterNames({serial: 'XXXX', parameter: 'YYYY'});</code> * * @return A JavaScript Command. */ public String generateCommand(String type, Map<String, ?> props) { StringBuilder buff = new StringBuilder(agentName); buff.append(".update").append(type).append("({"); for (Entry<String, ?> entry : props.entrySet()) { if (entry.getValue() instanceof String) { buff.append(entry.getKey()).append(": '").append(entry.getValue()).append("',"); } else { buff.append(entry.getKey()).append(": ").append(entry.getValue()).append(","); } } buff.deleteCharAt(buff.length() - 1); buff.append("});"); return buff.toString(); }
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(); }
private boolean instanceMapHasMocksInSeparateEntries( @Nonnull Object mock1, @Nonnull Object mock2) { boolean found1 = false; boolean found2 = false; for (Entry<Object, Object> entry : instanceMap.entrySet()) { if (!found1 && isInMapEntry(entry, mock1)) { found1 = true; } if (!found2 && isInMapEntry(entry, mock2)) { found2 = true; } if (found1 && found2) { return true; } } return false; }
/** * Updates the configuration from the filter config. * * @param filterConfig */ @SuppressWarnings("unchecked") public void updateConfigration(FilterConfig filterConfig) { Enumeration<String> paramEnum = filterConfig.getInitParameterNames(); while (paramEnum.hasMoreElements()) { String paramName = paramEnum.nextElement(); if (paramName.startsWith("r")) { try { if (!runOptions.containsKey(paramName)) throw new Exception("Invalid Parameter Name"); runOptions.put(paramName, Boolean.parseBoolean(filterConfig.getInitParameter(paramName))); } catch (Exception e) { log.warn("Init Parameter [" + paramName + "] is invalid or could not be set.", e); } } else if (paramName.startsWith("b")) { try { if (!batchOptions.containsKey(paramName)) throw new Exception("Invalid Parameter Name"); batchOptions.put(paramName, Integer.parseInt(filterConfig.getInitParameter(paramName))); } catch (Exception e) { log.warn("Init Parameter [" + paramName + "] is invalid or could not be set.", e); } } else if (paramName.startsWith("p")) { try { if (!parameterNames.containsKey(paramName)) throw new Exception("Invalid Parameter Name"); parameterNames.put(paramName, filterConfig.getInitParameter(paramName)); } catch (Exception e) { log.warn("Init Parameter [" + paramName + "] is invalid or could not be set.", e); } } else if ("listenerClassName".equals(paramName)) { listenerClassName = filterConfig.getInitParameter(paramName); } else if ("agentLogLevel".equals(paramName)) { try { agentLogLevel = Integer.parseInt(filterConfig.getInitParameter(paramName)); } catch (Exception e) { log.warn("Agent Log Level Could Not Be Set. Defaulting to [" + agentLogLevel + "].", e); } } else { log.warn("Init Parameter [" + paramName + "] was not recognized."); } } log.info("Completed AjaxMetrics Filter Configuration. Config is:\n" + toString()); inited = true; }
/** Creates a new AjaxMetricsFilterConfiguration populated with the default values. */ protected AjaxMetricsFilterConfiguration() { log = Logger.getLogger(getClass()); // ========================================================================== // Set default property values // ========================================================================== parameterNames.put(pUri, "AG_U"); parameterNames.put(pElapsed, "AG_E"); parameterNames.put(pConcurrent, "AG_C"); parameterNames.put(pException, "AG_X"); parameterNames.put(pHcode, "AG_H"); parameterNames.put(pDelta, "AG_D"); parameterNames.put(pFailure, "AG_F"); parameterNames.put(pInteractive, "AG_I"); parameterNames.put(pInteractiveTime, "AG_T"); parameterNames.put(pInteractiveCallbacks, "AG_B"); parameterNames.put(pSerialNumber, "AG_S"); parameterNames.put(pParameter, "AG_P"); parameterNames.put(pRunOption, "AG_O"); runOptions.put(reportInteractive, false); runOptions.put(reportDelta, true); runOptions.put(logging, false); runOptions.put(uploadBatch, false); runOptions.put(uploadInParams, false); batchOptions.put(batchTime, 40); batchOptions.put(batchSize, 5); }
/** * Returns the paraneter name for the passed value. * * @param s * @return The parameter name in effect. */ public String p(String s) { return parameterNames.get(s); }
public void registerInstanceFactoryForMockedType( @Nonnull Class<?> mockedType, @Nonnull InstanceFactory mockedInstanceFactory) { registerMockedClass(mockedType); mockedTypesAndInstances.put(mockedType, mockedInstanceFactory); }
/** * Looks up a parameter name. * * @param name The name of the parameter. * @return A name. */ public String getParamName(String name) { return parameterNames.get(name); }
/** * Looks up a run option value. * * @param name The name of the option. * @return a true or false. */ public boolean getRunOption(String name) { return runOptions.get(name); }
private void removeMockedClass(@Nonnull Class<?> mockedClass) { mockedTypesAndInstances.remove(mockedClass); mockedClasses.remove(mockedClass); }
@Nonnull Set<ClassIdentification> getTransformedClasses() { return transformedClasses.isEmpty() ? Collections.<ClassIdentification>emptySet() : new HashSet<ClassIdentification>(transformedClasses.keySet()); }
@Nullable Object getReplacementInstanceForMethodInvocation( @Nonnull Object invokedInstance, @Nonnull String methodNameAndDesc) { return methodNameAndDesc.charAt(0) == '<' ? null : replacementMap.get(invokedInstance); }
/** * Compute the minimal triangulation of the graph. Implementation of Algorithm MCS-M+ as described * in Berry et al. (2010), DOI:10.3390/a3020197 <a href="http://www.mdpi.com/1999-4893/3/2/197"> * http://www.mdpi.com/1999-4893/3/2/197</a> */ private void computeMinimalTriangulation() { // initialize chordGraph with same vertices as graph chordalGraph = new SimpleGraph<>(graph.getEdgeFactory()); for (V v : graph.vertexSet()) { chordalGraph.addVertex(v); } // initialize g' as subgraph of graph (same vertices and edges) final UndirectedGraph<V, E> gprime = copyAsSimpleGraph(graph); int s = -1; generators = new ArrayList<>(); meo = new LinkedList<>(); final Map<V, Integer> vertexLabels = new HashMap<>(); for (V v : gprime.vertexSet()) { vertexLabels.put(v, 0); } for (int i = 1, n = graph.vertexSet().size(); i <= n; i++) { V v = getMaxLabelVertex(vertexLabels); LinkedList<V> Y = new LinkedList<>(Graphs.neighborListOf(gprime, v)); if (vertexLabels.get(v) <= s) { generators.add(v); } s = vertexLabels.get(v); // Mark x reached and all other vertices of gprime unreached HashSet<V> reached = new HashSet<>(); reached.add(v); // mark neighborhood of x reached and add to reach(label(y)) HashMap<Integer, HashSet<V>> reach = new HashMap<>(); // mark y reached and add y to reach for (V y : Y) { reached.add(y); addToReach(vertexLabels.get(y), y, reach); } for (int j = 0; j < graph.vertexSet().size(); j++) { if (!reach.containsKey(j)) { continue; } while (reach.get(j).size() > 0) { // remove a vertex y from reach(j) V y = reach.get(j).iterator().next(); reach.get(j).remove(y); for (V z : Graphs.neighborListOf(gprime, y)) { if (!reached.contains(z)) { reached.add(z); if (vertexLabels.get(z) > j) { Y.add(z); E fillEdge = graph.getEdgeFactory().createEdge(v, z); fillEdges.add(fillEdge); addToReach(vertexLabels.get(z), z, reach); } else { addToReach(j, z, reach); } } } } } for (V y : Y) { chordalGraph.addEdge(v, y); vertexLabels.put(y, vertexLabels.get(y) + 1); } meo.addLast(v); gprime.removeVertex(v); vertexLabels.remove(v); } }
public void addTransformedClass( @Nonnull ClassIdentification classId, @Nonnull byte[] pretransformClassfile) { transformedClasses.put(classId, pretransformClassfile); }