code
stringlengths
73
34.1k
label
stringclasses
1 value
private List<AdvancedModelWrapper> enhanceUpdates(List<AdvancedModelWrapper> updates, Map<Object, AdvancedModelWrapper> updated, EKBCommit commit) { List<AdvancedModelWrapper> additionalUpdates = new ArrayList<AdvancedModelWrapper>(); for (AdvancedModelWrapper model : updates) { if (updated.containsKey(model.getCompleteModelOID())) { continue; // this model was already updated in this commit } if (model.isEngineeringObject()) { additionalUpdates.addAll(performEOModelUpdate(model.toEngineeringObject(), commit)); } additionalUpdates.addAll(getReferenceBasedUpdates(model, updated, commit)); } return additionalUpdates; }
java
private List<AdvancedModelWrapper> performEOModelUpdate(EngineeringObjectModelWrapper model, EKBCommit commit) { ModelDiff diff = createModelDiff(model.getUnderlyingModel(), model.getCompleteModelOID(), edbService, edbConverter); boolean referencesChanged = diff.isForeignKeyChanged(); boolean valuesChanged = diff.isValueChanged(); // TODO: OPENENGSB-3358, Make it possible to change references and values at the same time. Should be // no too big deal since we already know at this point which values of the model have been changed and // what the old and the new value for the changed properties are if (referencesChanged && valuesChanged) { throw new EKBException("Engineering Objects may be updated only at " + "references or at values not both in the same commit"); } if (referencesChanged) { reloadReferencesAndUpdateEO(diff, model); } else { return updateReferencedModelsByEO(model); } return new ArrayList<AdvancedModelWrapper>(); }
java
private List<AdvancedModelWrapper> updateReferencedModelsByEO(EngineeringObjectModelWrapper model) { List<AdvancedModelWrapper> updates = new ArrayList<AdvancedModelWrapper>(); for (Field field : model.getForeignKeyFields()) { try { AdvancedModelWrapper result = performMerge(model, loadReferencedModel(model, field)); if (result != null) { updates.add(result); } } catch (EDBException e) { LOGGER.debug("Skipped referenced model for field {}, since it does not exist.", field, e); } } return updates; }
java
private void reloadReferencesAndUpdateEO(ModelDiff diff, EngineeringObjectModelWrapper model) { for (ModelDiffEntry entry : diff.getDifferences().values()) { mergeEngineeringObjectWithReferencedModel(entry.getField(), model); } }
java
private List<AdvancedModelWrapper> getReferenceBasedUpdates(AdvancedModelWrapper model, Map<Object, AdvancedModelWrapper> updated, EKBCommit commit) throws EKBException { List<AdvancedModelWrapper> updates = new ArrayList<AdvancedModelWrapper>(); List<EDBObject> references = model.getModelsReferringToThisModel(edbService); for (EDBObject reference : references) { EDBModelObject modelReference = new EDBModelObject(reference, modelRegistry, edbConverter); AdvancedModelWrapper ref = updateEOByUpdatedModel(modelReference, model, updated); if (!updated.containsKey(ref.getCompleteModelOID())) { updates.add(ref); } } return updates; }
java
private AdvancedModelWrapper updateEOByUpdatedModel(EDBModelObject reference, AdvancedModelWrapper model, Map<Object, AdvancedModelWrapper> updated) { ModelDescription source = model.getModelDescription(); ModelDescription description = reference.getModelDescription(); AdvancedModelWrapper wrapper = updated.get(reference.getOID()); Object ref = null; if (wrapper == null) { ref = reference.getCorrespondingModel(); } else { ref = wrapper.getUnderlyingModel(); } Object transformResult = transformationEngine.performTransformation(source, description, model.getUnderlyingModel(), ref); return AdvancedModelWrapper.wrap(transformResult); }
java
private void enhanceCommitInserts(EKBCommit commit) throws EKBException { for (OpenEngSBModel model : commit.getInserts()) { AdvancedModelWrapper simple = AdvancedModelWrapper.wrap(model); if (simple.isEngineeringObject()) { performInsertEOLogic(simple.toEngineeringObject()); } } }
java
private void performInsertEOLogic(EngineeringObjectModelWrapper model) { for (Field field : model.getForeignKeyFields()) { mergeEngineeringObjectWithReferencedModel(field, model); } }
java
private AdvancedModelWrapper performMerge(AdvancedModelWrapper source, AdvancedModelWrapper target) { if (source == null || target == null) { return null; } ModelDescription sourceDesc = source.getModelDescription(); ModelDescription targetDesc = target.getModelDescription(); Object transformResult = transformationEngine.performTransformation(sourceDesc, targetDesc, source.getUnderlyingModel(), target.getUnderlyingModel()); AdvancedModelWrapper wrapper = AdvancedModelWrapper.wrap(transformResult); wrapper.removeOpenEngSBModelEntry(EDBConstants.MODEL_VERSION); return wrapper; }
java
private void mergeEngineeringObjectWithReferencedModel(Field field, EngineeringObjectModelWrapper model) { AdvancedModelWrapper result = performMerge(loadReferencedModel(model, field), model); if (result != null) { model = result.toEngineeringObject(); } }
java
public static <T> T createModel(Class<T> model, List<OpenEngSBModelEntry> entries) { if (!ModelWrapper.isModel(model)) { throw new IllegalArgumentException("The given class is no model"); } try { T instance = model.newInstance(); for (OpenEngSBModelEntry entry : entries) { if (tryToSetValueThroughField(entry, instance)) { continue; } if (tryToSetValueThroughSetter(entry, instance)) { continue; } ((OpenEngSBModel) instance).addOpenEngSBModelEntry(entry); } return instance; } catch (InstantiationException e) { LOGGER.error("InstantiationException while creating a new model instance.", e); } catch (IllegalAccessException e) { LOGGER.error("IllegalAccessException while creating a new model instance.", e); } catch (SecurityException e) { LOGGER.error("SecurityException while creating a new model instance.", e); } return null; }
java
private static boolean tryToSetValueThroughField(OpenEngSBModelEntry entry, Object instance) throws IllegalAccessException { try { Field field = instance.getClass().getDeclaredField(entry.getKey()); field.setAccessible(true); field.set(instance, entry.getValue()); field.setAccessible(false); return true; } catch (NoSuchFieldException e) { // if no field with this name exist, try to use the corresponding setter } catch (SecurityException e) { // if a security manager is installed which don't allow this change of a field value, try // to use the corresponding setter } return false; }
java
private static boolean tryToSetValueThroughSetter(OpenEngSBModelEntry entry, Object instance) throws IllegalAccessException { try { String setterName = getSetterName(entry.getKey()); Method method = instance.getClass().getMethod(setterName, entry.getType()); method.invoke(instance, entry.getValue()); return true; } catch (NoSuchMethodException e) { // if there exist no such method, then it is an entry meant for the model tail } catch (IllegalArgumentException e) { LOGGER.error("IllegalArgumentException while trying to set values for the new model.", e); } catch (InvocationTargetException e) { LOGGER.error("InvocationTargetException while trying to set values for the new model.", e); } return false; }
java
public static DestinationUrl createDestinationUrl(String destination) { String[] split = splitDestination(destination); String host = split[0].trim(); String jmsDestination = split[1].trim(); return new DestinationUrl(host, jmsDestination); }
java
public static <K, V> Map<K, List<V>> group(Collection<V> collection, Function<V, K> keyFn) { Map<K, List<V>> map = new HashMap<>(); for (V value : collection) { K key = keyFn.apply(value); if (map.get(key) == null) { map.put(key, new ArrayList<V>()); } map.get(key).add(value); } return map; }
java
public <T> JdbcIndex<T> buildIndex(Class<T> model) { JdbcIndex<T> index = new JdbcIndex<>(); index.setModelClass(model); index.setName(indexNameTranslator.translate(model)); index.setFields(buildFields(index)); return index; }
java
public static String extractAttributeValueNoEmptyCheck(Entry entry, String attributeType) { Attribute attribute = entry.get(attributeType); if (attribute == null) { return null; } try { return attribute.getString(); } catch (LdapInvalidAttributeValueException e) { throw new LdapRuntimeException(e); } }
java
public void removeSimilarClassesFromFile1() throws IOException { logging.info("Start reding cs File"); List<String> linescs1 = getFileLinesAsList(csFile1); logging.info("Start reding cs File"); List<String> linescs2 = getFileLinesAsList(csFile2); logging.info("Search classes"); List<String> classNames1 = searchClasses(linescs1); logging.info("Found " + classNames1.size() + " classes"); logging.info("Search classes"); List<String> classNames2 = searchClasses(linescs2); logging.info("Found " + classNames2.size() + " classes"); logging.info("Removing similarities from the file"); for (String name : findSimilarClassNames(classNames1, classNames2)) { linescs1 = removeLinesContainingClassname(linescs1, name); } logging.info("Remove Attributes, which stands alone"); linescs1 = removeAttributesNotBoundToClass(linescs1); if (!windows) { logging.info("Replace abstract classes with interfaces"); linescs1 = replaceAbstractClasses(linescs1); linescs2 = replaceAbstractClasses(linescs2); logging.info("Save files"); } replaceFilesWithNewContent(linescs1, csFile1); replaceFilesWithNewContent(linescs2, csFile2); }
java
public List<String> replaceAbstractClasses(List<String> lines) { List<String> result = new LinkedList<String>(); for (int i = 0; i < lines.size(); i++) { result.add(removeAbstract(lines.get(i))); } return result; }
java
private String getClassName(String line) { String result = line.substring(line.indexOf(CSHARP_CLASS_NAME) + CSHARP_CLASS_NAME.length()); if (result.contains("{")) { result = result.substring(0, result.indexOf("{")); } if (result.contains(":")) { result = result.substring(0, result.indexOf(":")); } return result.replaceAll("\\s", ""); }
java
public List<String> getFileLinesAsList(File f) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader( new DataInputStream(new FileInputStream(f)))); List<String> result = new LinkedList<String>(); String strLine; while ((strLine = br.readLine()) != null) { result.add(strLine); } br.close(); return result; }
java
public static void removeSimilaritiesAndSaveFiles(List<String> filepathes, Log logging, Boolean isWindows) throws IOException { List<File> files = new LinkedList<File>(); for (String path : filepathes) { files.add(new File(path)); } FileComparer fcomparer; for (int i = 0; i < files.size(); i++) { for (int y = i + 1; y < files.size(); y++) { fcomparer = new FileComparer(files.get(i), files.get(y), logging, isWindows); fcomparer.removeSimilarClassesFromFile1(); } } }
java
public static Filter getFilterForLocation(Class<?> clazz, String location, String context) throws IllegalArgumentException { String filter = makeLocationFilterString(location, context); return FilterUtils.makeFilter(clazz, filter); }
java
public static Filter getFilterForLocation(Class<?> clazz, String location) throws IllegalArgumentException { return getFilterForLocation(clazz, location, ContextHolder.get().getCurrentContextId()); }
java
public static Filter getFilterForLocation(String location, String context) throws IllegalArgumentException { String filter = makeLocationFilterString(location, context); try { return FrameworkUtil.createFilter(filter); } catch (InvalidSyntaxException e) { throw new IllegalArgumentException("location is invalid: " + location, e); } }
java
protected void checkInputSize(List<Object> input) throws TransformationOperationException { int inputCount = getOperationInputCount(); int inputSize = input.size(); if (inputCount == -2) { return; } else if (inputCount == -1 && input.size() < 1) { throw new TransformationOperationException("There must be at least one input value."); } else if (inputCount != -1 && inputSize != inputCount) { throw new TransformationOperationException( "The input values are not matching with the operation input count."); } }
java
protected String getParameterOrDefault(Map<String, String> parameters, String paramName, String defaultValue) throws TransformationOperationException { return getParameter(parameters, paramName, false, defaultValue); }
java
protected String getParameterOrException(Map<String, String> parameters, String paramName) throws TransformationOperationException { return getParameter(parameters, paramName, true, null); }
java
private String getParameter(Map<String, String> parameters, String paramName, boolean abortOnError, String defaultValue) throws TransformationOperationException { String value = parameters.get(paramName); if (value != null) { return value; } if (abortOnError) { String error = String.format("There is no parameter with the name %s present. The step will be ignored.", paramName); throw new TransformationOperationException(error); } logger.debug("There is no parameter with the name {} present. The value {} will be taken instead.", paramName, defaultValue); return defaultValue; }
java
protected Integer parseIntString(String string, boolean abortOnError, int def) throws TransformationOperationException { Integer integer = def; if (string == null) { logger.debug("Given string is empty so the default value is taken."); } try { integer = Integer.parseInt(string); } catch (NumberFormatException e) { StringBuilder builder = new StringBuilder(); builder.append("The string ").append(string).append(" is not a number. "); if (abortOnError) { builder.append("The step will be skipped."); } else { builder.append(def).append(" will be taken instead."); } logger.warn(builder.toString()); if (abortOnError) { throw new TransformationOperationException(builder.toString()); } } return integer; }
java
protected Matcher generateMatcher(String regex, String valueString) throws TransformationOperationException { if (regex == null) { throw new TransformationOperationException("No regex defined. The step will be skipped."); } try { Pattern pattern = Pattern.compile(regex); return pattern.matcher(valueString); } catch (PatternSyntaxException e) { String message = String.format("Given regex string %s can't be compiled. The step will be skipped.", regex); logger.warn(message); throw new TransformationOperationException(message); } }
java
protected void configureJaxbMarshaller(javax.xml.bind.Marshaller marshaller) throws PropertyException { marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, m_formatOutput); }
java
public Object getEntryValue(JPAEntry entry) { try { Class<?> typeClass = loadClass(entry.getType()); if (typeClass == null) { return entry.getValue(); } if (typeClass == Character.class) { if (entry.getValue().length() > 1) { LOGGER.warn("Too many chars in the string for a character type: " + entry.getValue()); LOGGER.warn("The first char of the string will be used."); return entry.getValue().charAt(0); } else if (entry.getValue().length() != 0) { return entry.getValue().charAt(0); } } Object result = invokeValueOf(typeClass, entry.getValue()); if (result != null) { return result; } Constructor<?> constructor = ClassUtils.getConstructorIfAvailable(typeClass, String.class); if (constructor != null) { return constructor.newInstance(entry.getValue()); } LOGGER.debug("DefaultConverterStep didn't find any possibility to convert entry {}. " + "The simple string value will be returned", entry); } catch (IllegalAccessException e) { LOGGER.error("IllegalAccessException when trying to create object of type {}", entry.getType(), e); } catch (InvocationTargetException e) { LOGGER.error("InvocationTargetException when trying to create object of type {}", entry.getType(), e); } catch (IllegalArgumentException e) { LOGGER.error("IllegalArgumentException when trying to create object of type {}", entry.getType(), e); } catch (InstantiationException e) { LOGGER.error("InstantiationException when trying to create object of type {}", entry.getType(), e); } return entry.getType(); }
java
private Class<?> loadClass(String className) { try { return EDBUtils.class.getClassLoader().loadClass(className); } catch (ClassNotFoundException e) { LOGGER.debug("Class {} can not be found by the EDB. This object type is not supported by the EDB." + " Maybe the conversion need to be done at model level.", className); } return null; }
java
private Object invokeValueOf(Class<?> clazz, String value) throws IllegalAccessException, InvocationTargetException { try { return MethodUtils.invokeExactStaticMethod(clazz, "valueOf", value); } catch (NoSuchMethodException e) { return null; } }
java
protected synchronized Expression getParsedExpression() { if (parsedExpression == null) { try { parsedExpression = EXPRESSION_PARSER.parseExpression(getExpression()); } catch (ParseException e) { throw new IllegalArgumentException("[" + getExpression() + "] is not a valid SpEL expression", e); } } return parsedExpression; }
java
public static VaadinConfirmDialog show(final UI ui, final String windowCaption, final String message, final String okCaption, final String cancelCaption, final Runnable r) { VaadinConfirmDialog d = getFactory().create(windowCaption, message, okCaption, cancelCaption, null); d.show(ui, new Listener() { private static final long serialVersionUID = 1L; public void onClose(VaadinConfirmDialog dialog) { if (dialog.isConfirmed()) { r.run(); } } }, true); return d; }
java
public final void show(final UI ui, final Listener listener, final boolean modal) { confirmListener = listener; center(); setModal(modal); ui.addWindow(this); }
java
public EKBCommit addInsert(Object insert) { if (insert != null) { checkIfModel(insert); inserts.add((OpenEngSBModel) insert); } return this; }
java
public EKBCommit addInserts(Collection<?> inserts) { if (inserts != null) { for (Object insert : inserts) { checkIfModel(insert); this.inserts.add((OpenEngSBModel) insert); } } return this; }
java
public EKBCommit addUpdate(Object update) { if (update != null) { checkIfModel(update); updates.add((OpenEngSBModel) update); } return this; }
java
public EKBCommit addUpdates(Collection<?> updates) { if (updates != null) { for (Object update : updates) { checkIfModel(update); this.updates.add((OpenEngSBModel) update); } } return this; }
java
public EKBCommit addDelete(Object delete) { if (delete != null) { checkIfModel(delete); deletes.add((OpenEngSBModel) delete); } return this; }
java
public EKBCommit addDeletes(Collection<?> deletes) { if (deletes != null) { for (Object delete : deletes) { checkIfModel(delete); this.deletes.add((OpenEngSBModel) delete); } } return this; }
java
public Set<OWLClassExpression> getNestedClassExpressions() { Set<OWLClassExpression> subConcepts = new HashSet<OWLClassExpression>(); for (OWLAxiom ax : justification) { subConcepts.addAll(ax.getNestedClassExpressions()); } return subConcepts; }
java
public static void store(Explanation<OWLAxiom> explanation, OutputStream os) throws IOException { try { OWLOntologyManager manager = OWLManager.createOWLOntologyManager(); OWLOntology ontology = manager.createOntology(explanation.getAxioms()); OWLDataFactory df = manager.getOWLDataFactory(); OWLAnnotationProperty entailmentMarkerAnnotationProperty = df.getOWLAnnotationProperty(ENTAILMENT_MARKER_IRI); OWLAnnotation entailmentAnnotation = df.getOWLAnnotation(entailmentMarkerAnnotationProperty, df.getOWLLiteral(true)); OWLAxiom annotatedEntailment = explanation.getEntailment().getAnnotatedAxiom(Collections.singleton(entailmentAnnotation)); manager.addAxiom(ontology, annotatedEntailment); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(os); OWLXMLDocumentFormat justificationOntologyFormat = new OWLXMLDocumentFormat(); manager.saveOntology(ontology, justificationOntologyFormat, bufferedOutputStream); } catch (OWLOntologyStorageException | OWLOntologyCreationException e) { throw new RuntimeException(e); } }
java
public static Explanation<OWLAxiom> load(InputStream is) throws IOException { try { OWLOntologyManager manager = OWLManager.createOWLOntologyManager(); OWLOntology ontology = manager.loadOntologyFromOntologyDocument(new BufferedInputStream(is)); OWLDataFactory df = manager.getOWLDataFactory(); OWLAnnotationProperty entailmentMarkerAnnotationProperty = df.getOWLAnnotationProperty(ENTAILMENT_MARKER_IRI); Set<OWLAxiom> justificationAxioms = new HashSet<OWLAxiom>(); OWLAxiom entailment = null; for(OWLAxiom ax : ontology.getAxioms()) { boolean isEntailmentAxiom = !ax.getAnnotations(entailmentMarkerAnnotationProperty).isEmpty(); if(!isEntailmentAxiom) { justificationAxioms.add(ax); } else { entailment = ax.getAxiomWithoutAnnotations(); } } if(entailment == null) { throw new IllegalStateException("Not a serialisation of an Explanation"); } return new Explanation<OWLAxiom>(entailment, justificationAxioms); } catch (OWLOntologyCreationException e) { throw new RuntimeException(e); } }
java
public static boolean hasAnnotation(CtClass clazz, String annotationName) { ClassFile cf = clazz.getClassFile2(); AnnotationsAttribute ainfo = (AnnotationsAttribute) cf.getAttribute(AnnotationsAttribute.invisibleTag); AnnotationsAttribute ainfo2 = (AnnotationsAttribute) cf.getAttribute(AnnotationsAttribute.visibleTag); return checkAnnotation(ainfo, ainfo2, annotationName); }
java
public static boolean hasAnnotation(CtField field, String annotationName) { FieldInfo info = field.getFieldInfo(); AnnotationsAttribute ainfo = (AnnotationsAttribute) info.getAttribute(AnnotationsAttribute.invisibleTag); AnnotationsAttribute ainfo2 = (AnnotationsAttribute) info.getAttribute(AnnotationsAttribute.visibleTag); return checkAnnotation(ainfo, ainfo2, annotationName); }
java
private static boolean checkAnnotation(AnnotationsAttribute invisible, AnnotationsAttribute visible, String annotationName) { boolean exist1 = false; boolean exist2 = false; if (invisible != null) { exist1 = invisible.getAnnotation(annotationName) != null; } if (visible != null) { exist2 = visible.getAnnotation(annotationName) != null; } return exist1 || exist2; }
java
private void checkBounds(String source, Integer from, Integer to) throws TransformationOperationException { Integer length = source.length(); if (from > to) { throw new TransformationOperationException( "The from parameter is bigger than the to parameter"); } if (from < 0 || from > length) { throw new TransformationOperationException( "The from parameter is not fitting to the size of the source"); } if (to < 0 || to > length) { throw new TransformationOperationException( "The to parameter is not fitting to the size of the source"); } }
java
private Integer getFromParameter(Map<String, String> parameters) throws TransformationOperationException { return getSubStringParameter(parameters, fromParam, 0); }
java
private Integer getToParameter(Map<String, String> parameters, Integer defaultValue) throws TransformationOperationException { return getSubStringParameter(parameters, toParam, defaultValue); }
java
private Integer getSubStringParameter(Map<String, String> parameters, String parameterName, Integer defaultValue) throws TransformationOperationException { String parameter = parameters.get(parameterName); if (parameter == null) { getLogger().debug("The {} parameter is not set, so the default value {} is taken.", parameterName, defaultValue); return defaultValue; } try { return Integer.parseInt(parameter); } catch (NumberFormatException e) { throw new TransformationOperationException("The " + parameterName + " parameter is not a number"); } }
java
@Override public void storeAll(Map mapEntries) { int batchSize = getBatchSize(); if (batchSize == 0 || mapEntries.size() < batchSize) { storeBatch(mapEntries); } else { Map batch = new HashMap(batchSize); while (!mapEntries.isEmpty()) { Iterator iter = mapEntries.entrySet().iterator(); while (iter.hasNext() && batch.size() < batchSize) { Map.Entry entry = (Map.Entry) iter.next(); batch.put(entry.getKey(), entry.getValue()); } storeBatch(batch); mapEntries.keySet().removeAll(batch.keySet()); batch.clear(); } } }
java
private static <E> List<OWLAxiom> getOrderedJustifications(List<OWLAxiom> mups, final Set<Explanation<E>> allJustifications) { Comparator<OWLAxiom> mupsComparator = new Comparator<OWLAxiom>() { public int compare(OWLAxiom o1, OWLAxiom o2) { // The checker that appears in most MUPS has the lowest index // in the list int occ1 = getOccurrences(o1, allJustifications); int occ2 = getOccurrences(o2, allJustifications); return -occ1 + occ2; } }; Collections.sort(mups, mupsComparator); return mups; }
java
private static <E> int getOccurrences(OWLAxiom ax, Set<Explanation<E>> axiomSets) { int count = 0; for (Explanation<E> explanation : axiomSets) { if (explanation.getAxioms().contains(ax)) { count++; } } return count; }
java
private void constructHittingSetTree(E entailment, Explanation<E> justification, Set<Explanation<E>> allJustifications, Set<Set<OWLAxiom>> satPaths, Set<OWLAxiom> currentPathContents, int maxExplanations) throws OWLException { // dumpHSTNodeDiagnostics(entailment, justification, allJustifications, currentPathContents); // We go through the current justifications, checker by checker, and extend the tree // with edges for each checker List<OWLAxiom> orderedJustification = getOrderedJustifications(new ArrayList<OWLAxiom>(justification.getAxioms()), allJustifications); while (!orderedJustification.isEmpty()) { OWLAxiom axiom = orderedJustification.get(0); orderedJustification.remove(0); if (allJustifications.size() == maxExplanations) { return; } // Remove the current checker from all the ontologies it is included // in module.remove(axiom); currentPathContents.add(axiom); boolean earlyTermination = false; // Early path termination. If our path contents are the superset of // the contents of a path then we can terminate here. for (Set<OWLAxiom> satPath : satPaths) { if (currentPathContents.containsAll(satPath)) { earlyTermination = true; break; } } if (!earlyTermination) { Explanation<E> newJustification = null; for (Explanation<E> foundJustification : allJustifications) { Set<OWLAxiom> foundMUPSCopy = new HashSet<OWLAxiom>(foundJustification.getAxioms()); foundMUPSCopy.retainAll(currentPathContents); if (foundMUPSCopy.isEmpty()) { // Justification reuse newJustification = foundJustification; break; } } if (newJustification == null) { newJustification = computeExplanation(entailment);//getExplanation(); } // Generate a new node - i.e. a new justification set if (axiom.isLogicalAxiom() && newJustification.contains(axiom)) { // How can this be the case??? throw new OWLRuntimeException("Explanation contains removed axiom: " + axiom + " (Working axioms contains axiom: " + module.contains(axiom) + ")"); } if (!newJustification.isEmpty()) { // Note that getting a previous justification does not mean // we // can stop. stopping here causes some justifications to be // missed boolean added = allJustifications.add(newJustification); if (added) { progressMonitor.foundExplanation(this, newJustification, allJustifications); } if (progressMonitor.isCancelled()) { return; } // Recompute priority here? // MutableTree<Explanation> node = new MutableTree<Explanation>(newJustification); // currentNode.addChild(node, checker); constructHittingSetTree(entailment, newJustification, allJustifications, satPaths, currentPathContents, maxExplanations); // We have found a new MUPS, so recalculate the ordering // axioms in the MUPS at the current level orderedJustification = getOrderedJustifications(orderedJustification, allJustifications); } else { // End of current path - add it to the list of paths satPaths.add(new HashSet<OWLAxiom>(currentPathContents)); Explanation exp = new Explanation<E>(entailment, new HashSet<OWLAxiom>(0)); MutableTree<Explanation> node = new MutableTree<Explanation>(exp); // currentNode.addChild(node, checker); // increment(checker); } } // Back track - go one level up the tree and run for the next checker currentPathContents.remove(axiom); // Done with the checker that was removed. Add it back in module.add(axiom); } }
java
protected void onMissingTypeVisit(Table table, IndexField<?> field) { if (!Introspector.isModelClass(field.getType())) { return; } Field idField = Introspector.getOpenEngSBModelIdField(field.getType()); if (idField == null) { LOG.warn("@Model class {} does not have an @OpenEngSBModelId", field.getType()); return; } DataType type = getTypeMap().getType(idField.getType()); if (type == null) { LOG.warn("@OpenEngSBModelId field {} has an unmapped type {}", field.getName(), field.getType()); return; } ((JdbcIndexField) field).setMappedType(type); Column column = new Column(getColumnNameTranslator().translate(field), type); table.addElement(column); // will hold the models OID onAfterFieldVisit(table, column, field); }
java
public Column set(Option option, boolean set) { if (set) { options.add(option); } else { options.remove(option); } return this; }
java
public void setStart(int x1, int y1) { start.x = x1; start.y = y1; needsRefresh = true; }
java
public void setEnd(int x2, int y2) { end.x = x2; end.y = y2; needsRefresh = true; }
java
public void draw(Graphics2D g) { if (needsRefresh) refreshCurve(); g.draw(curve); // Draws the main part of the arrow. drawArrow(g, end, control); // Draws the arrow head. drawText(g); }
java
public void drawHighlight(Graphics2D g) { if (needsRefresh) refreshCurve(); Graphics2D g2 = (Graphics2D) g.create(); g2.setStroke(new java.awt.BasicStroke(6.0f)); g2.setColor(HIGHLIGHT_COLOR); g2.draw(curve); g2.transform(affineToText); g2.fill(bounds); g2.dispose(); }
java
public void setLabel(String label) { this.label = label; // if (GRAPHICS == null) return; bounds = METRICS.getStringBounds(getLabel(), GRAPHICS); boolean upsideDown = end.x < start.x; float dx = (float) bounds.getWidth() / 2.0f; float dy = (curvy < 0.0f) ^ upsideDown ? METRICS.getAscent() : -METRICS .getDescent(); bounds.setRect(bounds.getX() - dx, bounds.getY() + dy, bounds .getWidth(), bounds.getHeight()); //System.out.println("Setting label" + label); }
java
private void drawArrow(Graphics g, Point head, Point away) { int endX, endY; double angle = Math.atan2((double) (away.x - head.x), (double) (away.y - head.y)); angle += ARROW_ANGLE; endX = ((int) (Math.sin(angle) * ARROW_LENGTH)) + head.x; endY = ((int) (Math.cos(angle) * ARROW_LENGTH)) + head.y; g.drawLine(head.x, head.y, endX, endY); angle -= 2 * ARROW_ANGLE; endX = ((int) (Math.sin(angle) * ARROW_LENGTH)) + head.x; endY = ((int) (Math.cos(angle) * ARROW_LENGTH)) + head.y; g.drawLine(head.x, head.y, endX, endY); }
java
public void refreshCurve() { // System.out.println("Curve refreshing"); needsRefresh = false; double lengthx = end.x - start.x; double lengthy = end.y - start.y; double centerx = ((double) (start.x + end.x)) / 2.0; double centery = ((double) (start.y + end.y)) / 2.0; double length = Math.sqrt(lengthx * lengthx + lengthy * lengthy); double factorx = length == 0.0 ? 0.0 : lengthx / length; double factory = length == 0.0 ? 0.0 : lengthy / length; control.x = (int) (centerx + curvy * HEIGHT * factory); control.y = (int) (centery - curvy * HEIGHT * factorx); high.x = (int) (centerx + curvy * HEIGHT * factory / 2.0); high.y = (int) (centery - curvy * HEIGHT * factorx / 2.0); curve.setCurve((float) start.x, (float) start.y, (float) control.x, (float) control.y, (float) end.x, (float) end.y); affineToText = new AffineTransform(); affineToText.translate(high.x, high.y); affineToText.rotate(Math.atan2(lengthy, lengthx)); if (end.x < start.x) affineToText.rotate(Math.PI); }
java
public Rectangle2D getBounds() { if (needsRefresh) refreshCurve(); Rectangle2D b = curve.getBounds(); Area area = new Area(bounds); area.transform(affineToText); b.add(area.getBounds()); return b; }
java
private boolean intersects(Point point, int fudge, QuadCurve2D.Float c) { if (!c.intersects(point.x - fudge, point.y - fudge, fudge << 1, fudge << 1)) return false; if (c.getFlatness() < fudge) return true; QuadCurve2D.Float f1 = new QuadCurve2D.Float(), f2 = new QuadCurve2D.Float(); c.subdivide(f1, f2); return intersects(point, fudge, f1) || intersects(point, fudge, f2); }
java
public HashMap<Variable,Object> chooseValues() { MultiVariable mv = (MultiVariable)myVariable; Variable[] internalVars = mv.getInternalVariables(); HashMap<Variable,Object> values = new HashMap<Variable,Object>(); for (Variable v: internalVars) { if (v instanceof MultiVariable) { MultiVariable nestedMv = (MultiVariable)v; MultiDomain nestedMd = nestedMv.getDomain(); HashMap<Variable,Object> nested = nestedMd.chooseValues(); for (Entry<Variable,Object> e : nested.entrySet()) { values.put(e.getKey(), e.getValue()); } } else { values.put(v,v.getDomain().chooseValue()); } } return values; }
java
public Rectangle getMinRectabgle(){ return new Rectangle((int)xLB.min, (int)yLB.min, (int)(xUB.min - xLB.min), (int)(yUB.min - yLB.min)); }
java
public Rectangle getMaxRectabgle(){ return new Rectangle((int)xLB.max, (int)yLB.max, (int)(xUB.max - xLB.max), (int)(yUB.max - yLB.max)); }
java
private boolean setLocation(String global, String context, Map<String, Object> properties) { String locationKey = "location." + context; Object propvalue = properties.get(locationKey); if (propvalue == null) { properties.put(locationKey, global); } else if (propvalue.getClass().isArray()) { Object[] locations = (Object[]) propvalue; if (ArrayUtils.contains(locations, global)) { return false; } Object[] newArray = Arrays.copyOf(locations, locations.length + 1); newArray[locations.length] = global; properties.put(locationKey, newArray); } else { if (((String) propvalue).equals(global)) { return false; } Object[] newArray = new Object[2]; newArray[0] = propvalue; newArray[1] = global; properties.put(locationKey, newArray); } return true; }
java
@SuppressWarnings({"unchecked"}) @Override public Map processAll(Set setEntries) { Map results = new LiteMap(); for (BinaryEntry entry : (Set<BinaryEntry>) setEntries) { Object result = processEntry(entry); if (result != NO_RESULT) { results.put(entry.getKey(), result); } } return results; }
java
protected Object processEntry(BinaryEntry entry) { Binary binCurrent = entry.getBinaryValue(); if (binCurrent == null && !fAllowInsert) { return fReturn ? null : NO_RESULT; } PofValue pvCurrent = getPofValue(binCurrent); PofValue pvNew = getPofValue("newValue"); Integer versionCurrent = (Integer) get(pvCurrent); Integer versionNew = (Integer) get(pvNew); if (versionCurrent.equals(versionNew)) { set(pvNew, versionNew + 1); entry.updateBinaryValue(pvNew.applyChanges()); return NO_RESULT; } return fReturn ? pvCurrent.getValue() : NO_RESULT; }
java
public static byte[] enhanceModel(byte[] byteCode, ClassLoader... loaders) throws IOException, CannotCompileException { return enhanceModel(byteCode, new Version("1.0.0"), loaders); }
java
public static byte[] enhanceModel(byte[] byteCode, Version modelVersion, ClassLoader... loaders) throws IOException, CannotCompileException { CtClass cc = doModelModifications(byteCode, modelVersion, loaders); if (cc == null) { return null; } byte[] newClass = cc.toBytecode(); cc.defrost(); cc.detach(); return newClass; }
java
private static CtClass doModelModifications(byte[] byteCode, Version modelVersion, ClassLoader... loaders) { if (!initiated) { initiate(); } CtClass cc = null; LoaderClassPath[] classloaders = new LoaderClassPath[loaders.length]; try { InputStream stream = new ByteArrayInputStream(byteCode); cc = cp.makeClass(stream); if (!JavassistUtils.hasAnnotation(cc, Model.class.getName())) { return null; } LOGGER.debug("Model to enhance: {}", cc.getName()); for (int i = 0; i < loaders.length; i++) { classloaders[i] = new LoaderClassPath(loaders[i]); cp.appendClassPath(classloaders[i]); } doEnhancement(cc, modelVersion); LOGGER.info("Finished model enhancing for class {}", cc.getName()); } catch (IOException e) { LOGGER.error("IOException while trying to enhance model", e); } catch (RuntimeException e) { LOGGER.error("RuntimeException while trying to enhance model", e); } catch (CannotCompileException e) { LOGGER.error("CannotCompileException while trying to enhance model", e); } catch (NotFoundException e) { LOGGER.error("NotFoundException while trying to enhance model", e); } catch (ClassNotFoundException e) { LOGGER.error("ClassNotFoundException while trying to enhance model", e); } finally { for (int i = 0; i < loaders.length; i++) { if (classloaders[i] != null) { cp.removeClassPath(classloaders[i]); } } } return cc; }
java
private static void doEnhancement(CtClass cc, Version modelVersion) throws CannotCompileException, NotFoundException, ClassNotFoundException { CtClass inter = cp.get(OpenEngSBModel.class.getName()); cc.addInterface(inter); addFields(cc); addGetOpenEngSBModelTail(cc); addSetOpenEngSBModelTail(cc); addRetrieveModelName(cc); addRetrieveModelVersion(cc, modelVersion); addOpenEngSBModelEntryMethod(cc); addRemoveOpenEngSBModelEntryMethod(cc); addRetrieveInternalModelId(cc); addRetrieveInternalModelTimestamp(cc); addRetrieveInternalModelVersion(cc); addToOpenEngSBModelValues(cc); addToOpenEngSBModelEntries(cc); cc.setModifiers(cc.getModifiers() & ~Modifier.ABSTRACT); }
java
private static void addFields(CtClass clazz) throws CannotCompileException, NotFoundException { CtField tail = CtField.make(String.format("private Map %s = new HashMap();", TAIL_FIELD), clazz); clazz.addField(tail); String loggerDefinition = "private static final Logger %s = LoggerFactory.getLogger(%s.class.getName());"; CtField logger = CtField.make(String.format(loggerDefinition, LOGGER_FIELD, clazz.getName()), clazz); clazz.addField(logger); }
java
private static void addGetOpenEngSBModelTail(CtClass clazz) throws CannotCompileException, NotFoundException { CtClass[] params = generateClassField(); CtMethod method = new CtMethod(cp.get(List.class.getName()), "getOpenEngSBModelTail", params, clazz); StringBuilder body = new StringBuilder(); body.append(createTrace("Called getOpenEngSBModelTail")) .append(String.format("return new ArrayList(%s.values());", TAIL_FIELD)); method.setBody(createMethodBody(body.toString())); clazz.addMethod(method); }
java
private static void addSetOpenEngSBModelTail(CtClass clazz) throws CannotCompileException, NotFoundException { CtClass[] params = generateClassField(List.class); CtMethod method = new CtMethod(CtClass.voidType, "setOpenEngSBModelTail", params, clazz); StringBuilder builder = new StringBuilder(); builder.append(createTrace("Called setOpenEngSBModelTail")) .append("if($1 != null) {for(int i = 0; i < $1.size(); i++) {") .append("OpenEngSBModelEntry entry = (OpenEngSBModelEntry) $1.get(i);") .append(String.format("%s.put(entry.getKey(), entry); } }", TAIL_FIELD)); method.setBody(createMethodBody(builder.toString())); clazz.addMethod(method); }
java
private static void addRetrieveModelName(CtClass clazz) throws CannotCompileException, NotFoundException { CtClass[] params = generateClassField(); CtMethod method = new CtMethod(cp.get(String.class.getName()), "retrieveModelName", params, clazz); StringBuilder builder = new StringBuilder(); builder.append(createTrace("Called retrieveModelName")) .append(String.format("return \"%s\";", clazz.getName())); method.setBody(createMethodBody(builder.toString())); clazz.addMethod(method); }
java
private static void addRetrieveInternalModelId(CtClass clazz) throws NotFoundException, CannotCompileException { CtField modelIdField = null; CtClass temp = clazz; while (temp != null) { for (CtField field : temp.getDeclaredFields()) { if (JavassistUtils.hasAnnotation(field, OpenEngSBModelId.class.getName())) { modelIdField = field; break; } } temp = temp.getSuperclass(); } CtClass[] params = generateClassField(); CtMethod valueMethod = new CtMethod(cp.get(Object.class.getName()), "retrieveInternalModelId", params, clazz); StringBuilder builder = new StringBuilder(); builder.append(createTrace("Called retrieveInternalModelId")); CtMethod idFieldGetter = getFieldGetter(modelIdField, clazz); if (modelIdField == null || idFieldGetter == null) { builder.append("return null;"); } else { builder.append(String.format("return %s();", idFieldGetter.getName())); } valueMethod.setBody(createMethodBody(builder.toString())); clazz.addMethod(valueMethod); CtMethod nameMethod = new CtMethod(cp.get(String.class.getName()), "retrieveInternalModelIdName", generateClassField(), clazz); if (modelIdField == null) { nameMethod.setBody(createMethodBody("return null;")); } else { nameMethod.setBody(createMethodBody("return \"" + modelIdField.getName() + "\";")); } clazz.addMethod(nameMethod); }
java
private static void addRetrieveInternalModelTimestamp(CtClass clazz) throws NotFoundException, CannotCompileException { CtClass[] params = generateClassField(); CtMethod method = new CtMethod(cp.get(Long.class.getName()), "retrieveInternalModelTimestamp", params, clazz); StringBuilder builder = new StringBuilder(); builder.append(createTrace("Called retrieveInternalModelTimestamp")) .append(String.format("return (Long) ((OpenEngSBModelEntry)%s.get(\"%s\")).getValue();", TAIL_FIELD, EDBConstants.MODEL_TIMESTAMP)); method.setBody(createMethodBody(builder.toString())); clazz.addMethod(method); }
java
private static void addRetrieveInternalModelVersion(CtClass clazz) throws NotFoundException, CannotCompileException { CtClass[] params = generateClassField(); CtMethod method = new CtMethod(cp.get(Integer.class.getName()), "retrieveInternalModelVersion", params, clazz); StringBuilder builder = new StringBuilder(); builder.append(createTrace("Called retrieveInternalModelVersion")) .append(String.format("return (Integer) ((OpenEngSBModelEntry)%s.get(\"%s\")).getValue();", TAIL_FIELD, EDBConstants.MODEL_VERSION)); method.setBody(createMethodBody(builder.toString())); clazz.addMethod(method); }
java
private static void addToOpenEngSBModelValues(CtClass clazz) throws NotFoundException, CannotCompileException, ClassNotFoundException { StringBuilder builder = new StringBuilder(); CtClass[] params = generateClassField(); CtMethod m = new CtMethod(cp.get(List.class.getName()), "toOpenEngSBModelValues", params, clazz); builder.append(createTrace("Add elements of the model tail")) .append("List elements = new ArrayList();\n") .append(createTrace("Add properties of the model")) .append(createModelEntryList(clazz)) .append("return elements;"); m.setBody(createMethodBody(builder.toString())); clazz.addMethod(m); }
java
private static void addToOpenEngSBModelEntries(CtClass clazz) throws NotFoundException, CannotCompileException, ClassNotFoundException { CtClass[] params = generateClassField(); CtMethod m = new CtMethod(cp.get(List.class.getName()), "toOpenEngSBModelEntries", params, clazz); StringBuilder builder = new StringBuilder(); builder.append(createTrace("Add elements of the model tail")) .append("List elements = new ArrayList();\n") .append(String.format("elements.addAll(%s.values());\n", TAIL_FIELD)) .append("elements.addAll(toOpenEngSBModelValues());\n") .append("return elements;"); m.setBody(createMethodBody(builder.toString())); clazz.addMethod(m); }
java
private static String createModelEntryList(CtClass clazz) throws NotFoundException, CannotCompileException { StringBuilder builder = new StringBuilder(); CtClass tempClass = clazz; while (tempClass != null) { for (CtField field : tempClass.getDeclaredFields()) { String property = field.getName(); if (property.equals(TAIL_FIELD) || property.equals(LOGGER_FIELD) || JavassistUtils.hasAnnotation(field, IgnoredModelField.class.getName())) { builder.append(createTrace(String.format("Skip property '%s' of the model", property))); continue; } builder.append(handleField(field, clazz)); } tempClass = tempClass.getSuperclass(); } return builder.toString(); }
java
private static String handleField(CtField field, CtClass clazz) throws NotFoundException, CannotCompileException { StringBuilder builder = new StringBuilder(); CtClass fieldType = field.getType(); String property = field.getName(); if (fieldType.equals(cp.get(File.class.getName()))) { return handleFileField(property, clazz); } CtMethod getter = getFieldGetter(field, clazz); if (getter == null) { LOGGER.warn(String.format("Ignoring property '%s' since there is no getter for it defined", property)); } else if (fieldType.isPrimitive()) { builder.append(createTrace(String.format("Handle primitive type property '%s'", property))); CtPrimitiveType primitiveType = (CtPrimitiveType) fieldType; String wrapperName = primitiveType.getWrapperName(); builder.append(String.format( "elements.add(new OpenEngSBModelEntry(\"%s\", %s.valueOf(%s()), %s.class));\n", property, wrapperName, getter.getName(), wrapperName)); } else { builder.append(createTrace(String.format("Handle property '%s'", property))) .append(String.format("elements.add(new OpenEngSBModelEntry(\"%s\", %s(), %s.class));\n", property, getter.getName(), fieldType.getName())); } return builder.toString(); }
java
private static String handleFileField(String property, CtClass clazz) throws NotFoundException, CannotCompileException { String wrapperName = property + "wrapper"; StringBuilder builder = new StringBuilder(); builder.append(createTrace(String.format("Handle File type property '%s'", property))) .append(String.format("if(%s == null) {", property)) .append(String.format("elements.add(new OpenEngSBModelEntry(\"%s\"", wrapperName)) .append(", null, FileWrapper.class));}\n else {") .append(String.format("FileWrapper %s = new FileWrapper(%s);\n", wrapperName, property)) .append(String.format("%s.serialize();\n", wrapperName)) .append(String.format("elements.add(new OpenEngSBModelEntry(\"%s\",%s,%s.getClass()));}\n", wrapperName, wrapperName, wrapperName)); addFileFunction(clazz, property); return builder.toString(); }
java
private static CtMethod getFieldGetter(CtField field, CtClass clazz) throws NotFoundException { if (field == null) { return null; } return getFieldGetter(field, clazz, false); }
java
private static CtMethod getFieldGetter(CtField field, CtClass clazz, boolean failover) throws NotFoundException { CtMethod method = new CtMethod(field.getType(), "descCreateMethod", new CtClass[]{}, clazz); String desc = method.getSignature(); String getter = getPropertyGetter(field, failover); try { return clazz.getMethod(getter, desc); } catch (NotFoundException e) { // try once again with getXXX instead of isXXX if (isBooleanType(field)) { return getFieldGetter(field, clazz, true); } LOGGER.debug(String.format("No getter with the name '%s' and the description '%s' found", getter, desc)); return null; } }
java
private static String getPropertyGetter(CtField field, boolean failover) throws NotFoundException { String property = field.getName(); if (!failover && isBooleanType(field)) { return String.format("is%s%s", Character.toUpperCase(property.charAt(0)), property.substring(1)); } else { return String.format("get%s%s", Character.toUpperCase(property.charAt(0)), property.substring(1)); } }
java
private static CtClass[] generateClassField(Class<?>... classes) throws NotFoundException { CtClass[] result = new CtClass[classes.length]; for (int i = 0; i < classes.length; i++) { result[i] = cp.get(classes[i].getName()); } return result; }
java
private static void addFileFunction(CtClass clazz, String property) throws NotFoundException, CannotCompileException { String wrapperName = property + "wrapper"; String funcName = "set"; funcName = funcName + Character.toUpperCase(wrapperName.charAt(0)); funcName = funcName + wrapperName.substring(1); String setterName = "set"; setterName = setterName + Character.toUpperCase(property.charAt(0)); setterName = setterName + property.substring(1); CtClass[] params = generateClassField(FileWrapper.class); CtMethod newFunc = new CtMethod(CtClass.voidType, funcName, params, clazz); newFunc.setBody("{ " + setterName + "($1.returnFile());\n }"); clazz.addMethod(newFunc); }
java
private static String urlEncodeParameter(String parameter) { try { return URLEncoder.encode(parameter, "UTF-8"); } catch (UnsupportedEncodingException ex) { log.warn("Could not encode parameter.", ex); } return parameter; }
java
public static void runWithContext(Runnable r) { try { browserStack.push(SwingFrame.getActiveWindow().getVisibleTab()); Subject.setCurrent(SwingFrame.getActiveWindow().getSubject()); r.run(); } finally { Subject.setCurrent(null); browserStack.pop(); } }
java
protected Reader createResourceReader(Resource resource) { try { return new InputStreamReader(resource.getInputStream()); } catch (IOException e) { throw new RuntimeException(e); } }
java
public void shutdown() { ClassLoader origClassLoader = Thread.currentThread().getContextClassLoader(); try { ClassLoader orientClassLoader = OIndexes.class.getClassLoader(); Thread.currentThread().setContextClassLoader(orientClassLoader); graph.close(); } finally { Thread.currentThread().setContextClassLoader(origClassLoader); } }
java