code
stringlengths
73
34.1k
label
stringclasses
1 value
private void nugetPackCommand() throws MojoExecutionException { List<String> commandList = new LinkedList<String>(); commandList.add(0, NUGET_COMMAND); commandList.add(1, "pack"); String[] command = commandList.toArray(new String[commandList.size()]); ProcessBuilder builder = new...
java
public IndexCommitBuilder insert(Object object) { updateModelClassSet(object); getInsertList(object.getClass()).add((OpenEngSBModel) object); return this; }
java
public IndexCommitBuilder update(Object object) { updateModelClassSet(object); getUpdateList(object.getClass()).add((OpenEngSBModel) object); return this; }
java
public IndexCommitBuilder delete(Object object) { updateModelClassSet(object); getDeleteList(object.getClass()).add((OpenEngSBModel) object); return this; }
java
private void checkNeededValues(TransformationDescription description) { String message = "The TransformationDescription doesn't contain a %s. Description loading aborted"; if (description.getSourceModel().getModelClassName() == null) { throw new IllegalArgumentException(String.format(message...
java
public Object transformObject(TransformationDescription description, Object source) throws InstantiationException, IllegalAccessException, ClassNotFoundException { return transformObject(description, source, null); }
java
public Object transformObject(TransformationDescription description, Object source, Object target) throws InstantiationException, IllegalAccessException, ClassNotFoundException { checkNeededValues(description); Class<?> sourceClass = modelRegistry.loadModel(description.getSourceModel()); ...
java
private void performTransformationStep(TransformationStep step) throws IllegalAccessException { try { TransformationOperation operation = operationLoader.loadTransformationOperationByName(step.getOperationName()); Object value = operation.performOperation(getSourceFieldVa...
java
private List<Object> getSourceFieldValues(TransformationStep step) throws Exception { List<Object> sources = new ArrayList<Object>(); for (String sourceField : step.getSourceFields()) { Object object = getObjectValue(sourceField, true); if (object == null) { Strin...
java
private void setObjectToTargetField(String fieldname, Object value) throws Exception { Object toWrite = null; if (fieldname.contains(".")) { String path = StringUtils.substringBeforeLast(fieldname, "."); toWrite = getObjectValue(path, false); } if (toWrite == null...
java
private Object getObjectValue(String fieldname, boolean fromSource) throws Exception { Object sourceObject = fromSource ? source : target; Object result = null; for (String part : StringUtils.split(fieldname, ".")) { if (isTemporaryField(part)) { result = loadObjectFr...
java
private Object loadObjectFromField(String fieldname, Object object, Object alternative) throws Exception { Object source = object != null ? object : alternative; try { return FieldUtils.readField(source, fieldname, true); } catch (Exception e) { throw new IllegalArgumentE...
java
private void writeObjectToField(String fieldname, Object value, Object object, Object alternative) throws Exception { Object target = object != null ? object : alternative; try { FieldUtils.writeField(target, fieldname, value, true); } catch (Exception e) { throw ...
java
private static Object waitForServiceFromTracker(ServiceTracker tracker, long timeout) throws OsgiServiceNotAvailableException { synchronized (tracker) { tracker.open(); try { return tracker.waitForService(timeout); } catch (InterruptedException e) { ...
java
protected double[] getDialogDimensions(String message, VaadinConfirmDialog.ContentMode style) { // Based on Reindeer style: double chrW = 0.51d; double chrH = 1.5d; double length = message != null? chrW * message.length() : 0; double rows = Math.ceil(length / MAX_WID...
java
private static int count(final String needle, final String haystack) { int count = 0; int pos = -1; while ((pos = haystack.indexOf(needle, pos + 1)) >= 0) { count++; } return count; }
java
private String format(double n) { NumberFormat nf = NumberFormat.getNumberInstance(Locale.ENGLISH); nf.setMaximumFractionDigits(1); nf.setGroupingUsed(false); return nf.format(n); }
java
public ModelDescription getModelDescription() { String modelType = object.getString(EDBConstants.MODEL_TYPE); String version = object.getString(EDBConstants.MODEL_TYPE_VERSION); return new ModelDescription(modelType, version); }
java
public OpenEngSBModel getCorrespondingModel() throws EKBException { ModelDescription description = getModelDescription(); try { Class<?> modelClass = modelRegistry.loadModel(description); return (OpenEngSBModel) edbConverter.convertEDBObjectToModel(modelClass, object); } ...
java
public Iterator iterator() { CsvPreference preferences = new CsvPreference.Builder(m_quoteChar, m_delimiterChar, m_endOfLineSymbols).build(); return new CsvIterator(new CsvListReader(m_reader, preferences), m_header); }
java
protected Serializable getCompiledExpression() { if (compiledExpression == null) { compiledExpression = MVEL.compileExpression(getExpression(), PARSER_CONTEXT); } return compiledExpression; }
java
protected Serializable getCompiledSetExpression() { if (compiledSetExpression == null) { compiledSetExpression = MVEL.compileSetExpression(getExpression(), PARSER_CONTEXT); } return compiledSetExpression; }
java
public void attachFormValidator(final Form<?> form, final FormValidator validator) { form.add(new AbstractFormValidator() { private static final long serialVersionUID = -4181095793820830517L; @Override public void validate(Form<?> form) { Map<String, FormCom...
java
protected Long performCommitLogic(EDBCommit commit) throws EDBException { if (!(commit instanceof JPACommit)) { throw new EDBException("The given commit type is not supported."); } if (commit.isCommitted()) { throw new EDBException("EDBCommit is already commitet."); ...
java
private void persistCommitChanges(JPACommit commit, Long timestamp) { commit.setTimestamp(timestamp); addModifiedObjectsToEntityManager(commit.getJPAObjects(), timestamp); commit.setCommitted(true); logger.debug("persisting JPACommit"); entityManager.persist(commit); logg...
java
private void addModifiedObjectsToEntityManager(List<JPAObject> modified, Long timestamp) { for (JPAObject update : modified) { update.setTimestamp(timestamp); entityManager.persist(update); } }
java
private void updateDeletedObjectsThroughEntityManager(List<String> oids, Long timestamp) { for (String id : oids) { EDBObject o = new EDBObject(id); o.updateTimestamp(timestamp); o.setDeleted(true); JPAObject j = EDBUtils.convertEDBObjectToJPAObject(o); ...
java
private void runBeginCommitHooks(EDBCommit commit) throws EDBException { for (EDBBeginCommitHook hook : beginCommitHooks) { try { hook.onStartCommit(commit); } catch (ServiceUnavailableException e) { // Ignore } catch (EDBException e) { ...
java
private EDBException runPreCommitHooks(EDBCommit commit) { EDBException exception = null; for (EDBPreCommitHook hook : preCommitHooks) { try { hook.onPreCommit(commit); } catch (ServiceUnavailableException e) { // Ignore } catch (EDBExc...
java
private Long runErrorHooks(EDBCommit commit, EDBException exception) throws EDBException { for (EDBErrorHook hook : errorHooks) { try { EDBCommit newCommit = hook.onError(commit, exception); if (newCommit != null) { return commit(newCommit); ...
java
private void runEDBPostHooks(EDBCommit commit) { for (EDBPostCommitHook hook : postCommitHooks) { try { hook.onPostCommit(commit); } catch (ServiceUnavailableException e) { // Ignore } catch (Exception e) { logger.error("Error w...
java
public boolean isLaconic(Explanation<E> justification) throws ExplanationException { // OBSERVATION: If a justification is laconic, then given its O+, there should be // one justification that is equal to itself. // Could optimise more here - we know that a laconic justification won't contain ...
java
public JPAEntry getEntry(String entryKey) { for (JPAEntry entry : entries) { if (entry.getKey().equals(entryKey)) { return entry; } } return null; }
java
public void removeEntry(String entryKey) { Iterator<JPAEntry> iter = entries.iterator(); while (iter.hasNext()) { if (iter.next().getKey().equals(entryKey)) { iter.remove(); return; } } }
java
private Object getLengthOfObject(Object object, String functionName) throws TransformationOperationException { try { Method method = object.getClass().getMethod(functionName); return method.invoke(object); } catch (NoSuchMethodException e) { StringBuilder builder = ne...
java
private <T> T read_(Class<T> clazz, Object id) { Map<String, Object> objects = objects(clazz); return (T) objects.get(id.toString()); }
java
public void deleteSubtreeExcludingRoot(Dn root) throws NoSuchNodeException, MissingParentException { existsCheck(root); try { EntryCursor entryCursor = connection.search(root, "(objectclass=*)", SearchScope.ONELEVEL); while (entryCursor.next()) { deleteSubtreeIncl...
java
public boolean exists(Dn dn) { try { return connection.exists(dn); } catch (LdapException e) { throw new LdapDaoException(e); } }
java
private QueryRequest createQueryRequest(String[] elements) { QueryRequest request = QueryRequest.create(); for (String element : elements) { String[] parts = StringUtils.split(element, ":", 2); parts[0] = parts[0].replace("\\", "\\\\"); parts[1] = parts[1].replace("\\...
java
public SequenceGenerator.SequenceBlock allocateBlock(int blockSize) { final long l = this.last; SequenceGenerator.SequenceBlock block = new SequenceGenerator.SequenceBlock(l + 1, l + blockSize); this.last = l + blockSize; return block; }
java
public void readExternal(PofReader reader) throws IOException { name = reader.readString(0); last = reader.readLong(1); }
java
public void writeExternal(PofWriter writer) throws IOException { writer.writeString(0, name); writer.writeLong(1, last); }
java
public Set<OWLClass> getRootUnsatisfiableClasses() throws ExplanationException { StructuralRootDerivedReasoner srd = new StructuralRootDerivedReasoner(manager, baseReasoner, reasonerFactory); Set<OWLClass> estimatedRoots = srd.getRootUnsatisfiableClasses(); cls2JustificationMap = new HashMap<OWL...
java
public static Connection getConnection(final String jndiName) throws FactoryException { Validate.notBlank(jndiName, "The validated character sequence 'jndiName' is null or empty"); // no need for defensive copies of Strings try { return DataSourceFactory.getDataSource(...
java
public static QueryRequest query(String key, Object value) { return QueryRequest.create().addParameter(key, value); }
java
public QueryRequest addParameter(String key, Object value) { if (parameters.get(key) == null) { parameters.put(key, Sets.newHashSet(value)); } else { parameters.get(key).add(value); } return this; }
java
@SuppressWarnings({ "rawtypes", "unchecked" }) private Predicate[] analyzeParamMap(CriteriaBuilder criteriaBuilder, Root from, Map<String, Object> param) { List<Predicate> predicates = new ArrayList<Predicate>(); for (Map.Entry<String, Object> entry : param.entrySet()) { String key = en...
java
private void batchImport() { m_jdbcTemplate.batchUpdate(createInsertQuery(), new BatchPreparedStatementSetter() { public void setValues( PreparedStatement ps, int i) ...
java
private String createInsertQuery() { StringBuilder query = new StringBuilder(); query.append("insert into ").append(m_tableName) .append("(").append(m_propertyNames[0]); for (int i = 1; i < m_propertyNames.length; i++) { query.append(",").append(m_propertyNames[i...
java
public static <T extends Annotation> Method findMethodWithAnnotation(Class<?> clazz, Class<T> annotationType) { Method annotatedMethod = null; for (Method method : clazz.getDeclaredMethods()) { T annotation = AnnotationUtils.findAnnotation(method, annotationType); if (annotation ...
java
public static Object invokeMethod(Object object, Method method, Object... args) throws Throwable { try { return method.invoke(object, args); } catch (InvocationTargetException e) { throw e.getTargetException(); } }
java
public static void validateReturnType(Method method, Class<? extends Annotation> annotationType, Class<?> expectedReturnType) { if (!method.getReturnType().equals(expectedReturnType)) { throw new BeanCreationException("Method " + method.getName() + " annotat...
java
public static void validateArgument(Method method, Class<? extends Annotation> annotationType, Class<?> expectedParameterType) { if (method.getParameterTypes().length != 1 || !method.getParameterTypes()[0].equals(expectedParameterType)) { throw new BeanCreatio...
java
protected Object getValue() { Object value = this.value; if (value == null) { this.value = value = fromBinary("value"); } return value; }
java
public CuratorFramework newCurator() { // Make all of the curator threads daemon threads so they don't block the JVM from terminating. Also label them // with the ensemble they're connecting to, in case someone is trying to sort through a thread dump. ThreadFactory threadFactory = new ThreadFac...
java
public static Class<?> getTypeArgument(Class<?> clazz, Class<?> interfce) { Map<Type, Type> resolvedTypes = new HashMap<Type, Type>(); Type type = clazz; while (!declaresInterface(getClass(type), interfce)) { if (type instanceof Class) { type = ((Class<?>) type).getGenericSuperclass(); } else { P...
java
public static List<Entry> assignmentStructure(Assignment assignment) { List<Entry> entryList = new LinkedList<>(); entryList.add(namedObject(DnFactory.assignment(assignment))); entryList.add(namedDescriptiveObject(DnFactory.assignmentProject(assignment), assignment.getProject())); entryL...
java
public static List<Entry> permissionStructure(Permission permission) { List<Entry> entryList = new LinkedList<>(); entryList.add(namedObject(DnFactory.permission(permission))); entryList.add(namedDescriptiveObject(DnFactory.permissionAction(permission), permission.getAction())); entryLis...
java
public static List<Entry> projectStructure(Project project) { List<Entry> entryList = new LinkedList<>(); entryList.add(namedObject(DnFactory.project(project))); entryList.addAll(createProjectAttributesEntries(project)); return entryList; }
java
public static List<Entry> roleStructure(Role role) { List<Entry> entryList = new LinkedList<>(); entryList.add(namedObject(DnFactory.role(role))); entryList.addAll(createRolePermissionsEntries(role)); entryList.addAll(createRoleSubrolesEntries(role)); return entryList; }
java
public BufferedImage getBufferedImage(int width, int height) { BufferedImage bi = chart.createBufferedImage(width, height); return bi; }
java
@SuppressWarnings("deprecation") private JFreeChart createChart(CategoryDataset dataset) { // String s = name; String s = null; String tit = null; String ax = null; // if (first) // tit = title + " (EST)"; // else if (last) // ax = "Time"; tit = this.name; chart = ChartFactory...
java
private CategoryDataset createDataset() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); startTimes = new Long[stl.getPulses().length+1]; startTimes[0] = new Long(0); for( int i = 1 ; i < startTimes.length ; i++ ) { startTimes[i] = stl.getPulses()[i-1]; } durations = new Lo...
java
public static String extractAttributeEmptyCheck(Entry entry, String attributeType) { Attribute attribute = entry.get(attributeType); Attribute emptyFlagAttribute = entry.get(SchemaConstants.EMPTY_FLAG_ATTRIBUTE); boolean empty = false; try { if (attribute != null) { ...
java
public static List<String> extractAttributeEmptyCheck(List<Entry> entries, String attributeType) { List<String> result = new LinkedList<String>(); for (Entry e : entries) { result.add(extractAttributeEmptyCheck(e, attributeType)); } return result; }
java
public static List<String> extractAttributeEmptyCheck(SearchCursor cursor, String attributeType) { List<String> result = new LinkedList<String>(); try { while (cursor.next()) { Entry entry = cursor.getEntry(); result.add(extractAttributeEmptyCheck(entry, attri...
java
private void createObjectDiffs() throws EDBException { diff = new HashMap<String, EDBObjectDiff>(); List<EDBObject> tempList = new ArrayList<EDBObject>(); for (EDBObject o : this.endState) { tempList.add(o); } addModifiedOrDeletedObjects(tempList); addNewObje...
java
private void addModifiedOrDeletedObjects(List<EDBObject> tempList) { for (EDBObject a : this.startState) { String oid = a.getOID(); EDBObject b = removeIfExist(oid, tempList); ObjectDiff odiff = new ObjectDiff(this.startCommit, this.endCommit, a, b); if (odiff.get...
java
private void addNewObjects(List<EDBObject> tempList) { for (EDBObject b : tempList) { String oid = b.getOID(); ObjectDiff odiff = new ObjectDiff(this.startCommit, this.endCommit, null, b); if (odiff.getDifferenceCount() > 0) { diff.put(oid, odiff); ...
java
private EDBObject removeIfExist(String oid, List<EDBObject> tempList) { Iterator<EDBObject> iterator = tempList.iterator(); while (iterator.hasNext()) { EDBObject obj = iterator.next(); if (obj.getOID().equals(oid)) { iterator.remove(); return obj;...
java
private boolean compareRelation(RCCConstraint first, RCCConstraint second) { boolean existed = false; for (int i = 0; i < first.types.length; i++) { existed = false; for (int j = 0; j < second.types.length; j++) { if(first.types[i] == second.types[j]) existed = true; } if(!exist...
java
private void runPersistingLogic(EKBCommit commit, boolean check, UUID expectedContextHeadRevision, boolean headRevisionCheck) throws SanityCheckException, EKBException { String contextId = ContextHolder.get().getCurrentContextId(); try { lockContext(contextId); if (he...
java
private void performRevertLogic(String revision, UUID expectedContextHeadRevision, boolean expectedHeadCheck) { String contextId = ""; try { EDBCommit commit = edbService.getCommitByRevision(revision); contextId = commit.getContextId(); lockContext(contextId); ...
java
private void lockContext(String contextId) throws EKBConcurrentException { if (mode == ContextLockingMode.DEACTIVATED) { return; } synchronized (activeWritingContexts) { if (activeWritingContexts.contains(contextId)) { throw new EKBConcurrentException("The...
java
private void checkForContextHeadRevision(String contextId, UUID expectedHeadRevision) throws EKBConcurrentException { if (!Objects.equal(edbService.getLastRevisionNumberOfContext(contextId), expectedHeadRevision)) { throw new EKBConcurrentException("The current revision of the context does n...
java
private void releaseContext(String contextId) { if (mode == ContextLockingMode.DEACTIVATED) { return; } synchronized (activeWritingContexts) { activeWritingContexts.remove(contextId); } }
java
private void runEKBPreCommitHooks(EKBCommit commit) throws EKBException { for (EKBPreCommitHook hook : preCommitHooks) { try { hook.onPreCommit(commit); } catch (EKBException e) { throw new EKBException("EDBException is thrown in a pre commit hook.", e); ...
java
private void runEKBPostCommitHooks(EKBCommit commit) throws EKBException { for (EKBPostCommitHook hook : postCommitHooks) { try { hook.onPostCommit(commit); } catch (Exception e) { LOGGER.warn("An exception is thrown in a EKB post commit hook.", e); ...
java
private void runEKBErrorHooks(EKBCommit commit, EKBException exception) { if (exception != null) { for (EKBErrorHook hook : errorHooks) { hook.onError(commit, exception); } throw exception; } }
java
private void performPersisting(ConvertedCommit commit, EKBCommit source) throws EKBException { try { EDBCommit ci = edbService.createEDBCommit(commit.getInserts(), commit.getUpdates(), commit.getDeletes()); ci.setDomainId(source.getDomainId()); ci.setConnectorId(source.getCon...
java
private List<String> convertEDBObjectList(List<EDBObject> objects) { List<String> oids = new ArrayList<>(); for (EDBObject object : objects) { oids.add(object.getOID()); } return oids; }
java
private Set<ModelDescription> scanBundleForModels(Bundle bundle) { Set<ModelDescription> models = new HashSet<ModelDescription>(); if (!shouldSkipBundle(bundle)) { models = loadModelsOfBundle(bundle); } return models; }
java
private Set<ModelDescription> loadModelsOfBundle(Bundle bundle) { Enumeration<URL> classEntries = bundle.findEntries("/", "*.class", true); Set<ModelDescription> models = new HashSet<ModelDescription>(); if (classEntries == null) { LOGGER.debug("Found no classes in the bundle {}", bu...
java
private boolean isModelClass(String classname, Bundle bundle) { LOGGER.debug("Check if class '{}' is a model class", classname); Class<?> clazz; try { clazz = bundle.loadClass(classname); } catch (ClassNotFoundException e) { LOGGER.warn("Bundle could not load its ...
java
private String extractClassName(URL classURL) { String path = classURL.getPath(); return path .replaceAll("^/", "") .replaceAll(".class$", "") .replaceAll("\\/", "."); }
java
public List<User> findAllUsers() { List<User> list = new ArrayList<>(); List<String> usernames; try { usernames = readLines(usersFile); } catch (IOException e) { throw new FileBasedRuntimeException(e); } for (String username : usernames) { ...
java
private int rightmostIndexBelowMax() { for (int i = r-1; i>=0; i--) if (index[i] < n - r + i) return i; return -1; }
java
public static void setLevel(Level l) { for (Logger log : loggers.values()) log.setLevel(l); globalLevel = l; }
java
public static void setLevel(Class<?> c, Level l) /* throws LoggerNotDefined */ { if (!loggers.containsKey(c)) tempLevels.put(c, l); else loggers.get(c).setLevel(l); //System.out.println("Set level " + l + " for logger " + loggers.get(c).getName()); }
java
public void setImage(BufferedImage im) { icon.setImage(im); if (image == null) { this.image = im; // this.setSize(image.getWidth(), image.getHeight()); int panelX = image.getWidth(); int panelY = image.getHeight(); panel.setSize(panelX, panelY); // Toolkit tk = Toolkit.getDefaultToolkit(...
java
public List<Assignment> findAllAssignments() { List<Assignment> list = new ArrayList<>(); List<String> assignmentStrings; try { assignmentStrings = readLines(assignmentsFile); } catch (IOException e) { throw new FileBasedRuntimeException(e); } for...
java
private static void logValue(final String key, final String value) { // Fortify will report a violation here because of disclosure of potentially confidential information. // However, the configuration keys are not confidential, which makes this a non-issue / false positive. if (LOG.isInfoEnabl...
java
private static void logDefault(final String key, final String defaultValue) { // Fortify will report a violation here because of disclosure of potentially confidential information. // However, neither the configuration keys nor the default propsbuilder values are confidential, which makes // th...
java
@SuppressWarnings({"PMD.UseObjectForClearerAPI"}) // CHECKSTYLE:ON private static void logDefault(final String key, final String invalidValue, final String validationError, final String defaultValue) { ...
java
public int getSequenceNumber(Coordinate coord) { int minIndex = 0; double minDist = Double.MAX_VALUE; for (int i = 0; i < this.getPositions().length; i++) { if (this.getPositions()[i].distance(coord) < minDist) { minDist = this.getPositions()[i].distance(coord); minIndex = i; } } return minIndex...
java
private void enhanceEKBCommit(EKBCommit commit) throws EKBException { LOGGER.debug("Started to enhance the EKBCommit with Engineering Object information"); enhanceCommitInserts(commit); enhanceCommitUpdates(commit); // TODO: OPENENGSB-3357, consider also deletions in the enhancement ...
java
private void enhanceCommitUpdates(EKBCommit commit) throws EKBException { Map<Object, AdvancedModelWrapper> updated = new HashMap<Object, AdvancedModelWrapper>(); List<AdvancedModelWrapper> result = recursiveUpdateEnhancement( convertOpenEngSBModelList(commit.getUpdates()), updated, commit);...
java
private List<AdvancedModelWrapper> convertOpenEngSBModelList(List<OpenEngSBModel> models) { List<AdvancedModelWrapper> wrappers = new ArrayList<AdvancedModelWrapper>(); for (OpenEngSBModel model : models) { wrappers.add(AdvancedModelWrapper.wrap(model)); } return wrappers; ...
java
private List<OpenEngSBModel> convertSimpleModelWrapperList(List<AdvancedModelWrapper> wrappers) { List<OpenEngSBModel> models = new ArrayList<OpenEngSBModel>(); for (AdvancedModelWrapper wrapper : wrappers) { models.add(wrapper.getUnderlyingModel()); } return models; }
java
private List<AdvancedModelWrapper> recursiveUpdateEnhancement(List<AdvancedModelWrapper> updates, Map<Object, AdvancedModelWrapper> updated, EKBCommit commit) { List<AdvancedModelWrapper> additionalUpdates = enhanceUpdates(updates, updated, commit); for (AdvancedModelWrapper model : updates)...
java