code
stringlengths 73
34.1k
| label
stringclasses 1
value |
---|---|
public static Expression createExpression(String expression) {
try {
return INSTANCE.ctorExpression.newInstance(expression);
}
catch (Exception e) {
throw new RuntimeException(e);
}
} | java |
public static Extractor createExtractor(String expression) {
try {
return INSTANCE.ctorExtractor.newInstance(expression);
}
catch (Exception e) {
throw new RuntimeException(e);
}
} | java |
public static Updater createUpdater(String expression) {
try {
return INSTANCE.ctorUpdater.newInstance(expression);
}
catch (Exception e) {
throw new RuntimeException(e);
}
} | java |
public static Condition createCondition(String expression) {
try {
return INSTANCE.ctorCondition.newInstance(expression);
}
catch (Exception e) {
throw new RuntimeException(e);
}
} | java |
protected Constructor getConstructor(Class type) {
try {
return type.getConstructor(String.class);
}
catch (NoSuchMethodException e) {
throw new RuntimeException(
"Unable to find a constructor that accepts"
+ " a single String argument in the "
+ type.getName() + " class.", e);
}
} | java |
public static EngineeringObjectModelWrapper enhance(AdvancedModelWrapper model) {
if (!model.isEngineeringObject()) {
throw new IllegalArgumentException("The model of the AdvancedModelWrapper is no EngineeringObject");
}
return new EngineeringObjectModelWrapper(model.getUnderlyingModel());
} | java |
public List<Field> getForeignKeyFields() {
List<Field> fields = new ArrayList<Field>();
for (Field field : model.getClass().getDeclaredFields()) {
if (field.isAnnotationPresent(OpenEngSBForeignKey.class)) {
fields.add(field);
}
}
return fields;
} | java |
public AdvancedModelWrapper loadReferencedModel(Field field, ModelRegistry modelRegistry,
EngineeringDatabaseService edbService, EDBConverter edbConverter) {
try {
ModelDescription description = getModelDescriptionFromField(field);
String modelKey = (String) FieldUtils.readField(field, model, true);
if (modelKey == null) {
return null;
}
modelKey = appendContextId(modelKey);
Class<?> sourceClass = modelRegistry.loadModel(description);
Object model = edbConverter.convertEDBObjectToModel(sourceClass,
edbService.getObject(modelKey));
return new AdvancedModelWrapper((OpenEngSBModel) model);
} catch (SecurityException e) {
throw new EKBException(generateErrorMessage(field), e);
} catch (IllegalArgumentException e) {
throw new EKBException(generateErrorMessage(field), e);
} catch (IllegalAccessException e) {
throw new EKBException(generateErrorMessage(field), e);
} catch (ClassNotFoundException e) {
throw new EKBException(generateErrorMessage(field), e);
}
} | java |
private ModelDescription getModelDescriptionFromField(Field field) {
OpenEngSBForeignKey key = field.getAnnotation(OpenEngSBForeignKey.class);
ModelDescription description = new ModelDescription(key.modelType(), key.modelVersion());
return description;
} | java |
public synchronized Long generateId() {
if (sequenceBlock == null || !sequenceBlock.hasNext()) {
sequenceBlock = allocateSequenceBlock();
}
return sequenceBlock.next();
} | java |
private String performRemoveLeading(String source, Integer length, Matcher matcher) {
if (length != null && length != 0) {
matcher.region(0, length);
}
if (matcher.find()) {
String matched = matcher.group();
return source.substring(matched.length());
}
return source;
} | java |
public void set( float radians )
{
float c = (float)StrictMath.cos( radians );
float s = (float)StrictMath.sin( radians );
m00 = c;
m01 = -s;
m10 = s;
m11 = c;
} | java |
protected DataType put(Class<?> clazz, int type, String name) {
DataType dataType = new DataType(type, name);
map.put(clazz, dataType);
return dataType;
} | java |
public static byte[] decrypt(byte[] text, Key key) throws DecryptionException {
return decrypt(text, key, key.getAlgorithm());
} | java |
public static byte[] decrypt(byte[] text, Key key, String algorithm) throws DecryptionException {
Cipher cipher;
try {
LOGGER.trace("start decrypting text using {} cipher", algorithm);
cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.DECRYPT_MODE, key);
LOGGER.trace("initialized decryption with key of type {}", key.getClass());
} catch (GeneralSecurityException e) {
throw new IllegalArgumentException("unable to initialize cipher for algorithm " + algorithm, e);
}
try {
return cipher.doFinal(text);
} catch (GeneralSecurityException e) {
throw new DecryptionException("unable to decrypt data using algorithm " + algorithm, e);
}
} | java |
public static byte[] encrypt(byte[] text, Key key) throws EncryptionException {
return encrypt(text, key, key.getAlgorithm());
} | java |
public static byte[] encrypt(byte[] text, Key key, String algorithm) throws EncryptionException {
Cipher cipher;
try {
LOGGER.trace("start encrypting text using {} cipher", algorithm);
cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.ENCRYPT_MODE, key);
LOGGER.trace("initialized encryption with key of type {}", key.getClass());
} catch (GeneralSecurityException e) {
throw new IllegalArgumentException("unable to initialize cipher for algorithm " + algorithm, e);
}
try {
return cipher.doFinal(text);
} catch (GeneralSecurityException e) {
throw new EncryptionException("unable to encrypt data using algorithm " + algorithm, e);
}
} | java |
public static byte[] sign(byte[] text, PrivateKey key, String algorithm) throws SignatureException {
Signature signature;
try {
signature = Signature.getInstance(algorithm);
signature.initSign(key);
} catch (GeneralSecurityException e) {
throw new IllegalArgumentException("cannot initialize signature for algorithm " + algorithm, e);
}
signature.update(text);
return signature.sign();
} | java |
public static boolean verify(byte[] text, byte[] signatureValue, PublicKey key, String algorithm)
throws SignatureException {
Signature signature;
try {
signature = Signature.getInstance(algorithm);
signature.initVerify(key);
} catch (GeneralSecurityException e) {
throw new IllegalArgumentException("cannot initialize signature for algorithm " + algorithm, e);
}
signature.update(text);
return signature.verify(signatureValue);
} | java |
protected synchronized Object getCompiledExpression() {
if (compiledExpression == null) {
try {
compiledExpression = Ognl.parseExpression(getExpression());
}
catch (OgnlException e) {
throw new IllegalArgumentException("[" + getExpression() + "] is not a valid OGNL expression", e);
}
}
return compiledExpression;
} | java |
public static <T> T view(Object completeObject, T viewObject) {
if (completeObject == null) return null;
Map<String, PropertyInterface> propertiesOfCompleteObject = FlatProperties.getProperties(completeObject.getClass());
Map<String, PropertyInterface> properties = FlatProperties.getProperties(viewObject.getClass());
for (Map.Entry<String, PropertyInterface> entry : properties.entrySet()) {
PropertyInterface property = propertiesOfCompleteObject.get(entry.getKey());
Object value = property != null ? property.getValue(completeObject) : readByGetMethod(completeObject, entry.getKey());
entry.getValue().setValue(viewObject, value);
}
return viewObject;
} | java |
public static <T> T viewed(View<T> viewObject) {
if (viewObject == null) return null;
@SuppressWarnings("unchecked")
Class<T> viewedClass = (Class<T>) getViewedClass(viewObject.getClass());
Object id = IdUtils.getId(viewObject);
if (id == null) {
return null;
}
return Backend.read(viewedClass, id);
} | java |
public static ModelDiff createModelDiff(OpenEngSBModel before, OpenEngSBModel after) {
ModelDiff diff = new ModelDiff(before, after);
calculateDifferences(diff);
return diff;
} | java |
public static ModelDiff createModelDiff(OpenEngSBModel updated, String completeModelId,
EngineeringDatabaseService edbService, EDBConverter edbConverter) {
EDBObject queryResult = edbService.getObject(completeModelId);
OpenEngSBModel old = edbConverter.convertEDBObjectToModel(updated.getClass(), queryResult);
ModelDiff diff = new ModelDiff(old, updated);
calculateDifferences(diff);
return diff;
} | java |
private static void calculateDifferences(ModelDiff diff) {
Class<?> modelClass = diff.getBefore().getClass();
for (Field field : modelClass.getDeclaredFields()) {
if (field.getName().equals(ModelUtils.MODEL_TAIL_FIELD_NAME)) {
continue;
}
try {
Object before = FieldUtils.readField(field, diff.getBefore(), true);
Object after = FieldUtils.readField(field, diff.getAfter(), true);
if (!Objects.equal(before, after)) {
diff.addDifference(field, before, after);
}
} catch (IllegalAccessException e) {
LOGGER.warn("Skipped field '{}' because of illegal access to it", field.getName(), e);
}
}
} | java |
public void addDifference(Field field, Object before, Object after) {
ModelDiffEntry entry = new ModelDiffEntry();
entry.setBefore(before);
entry.setAfter(after);
entry.setField(field);
differences.put(field, entry);
} | java |
public boolean isForeignKeyChanged() {
return CollectionUtils.exists(differences.values(), new Predicate() {
@Override
public boolean evaluate(Object object) {
return ((ModelDiffEntry) object).isForeignKey();
}
});
} | java |
public boolean containsPoint(Coordinate point) {
Point p = new GeometryFactory().createPoint(point);
return this.getGeometry().contains(p);
} | java |
public static <ReturnType> ReturnType executeWithSystemPermissions(Callable<ReturnType> task)
throws ExecutionException {
ContextAwareCallable<ReturnType> contextAwareCallable = new ContextAwareCallable<ReturnType>(task);
Subject newsubject = new Subject.Builder().buildSubject();
newsubject.login(new RootAuthenticationToken());
try {
return newsubject.execute(contextAwareCallable);
} finally {
newsubject.logout();
}
} | java |
public static void executeWithSystemPermissions(Runnable task) {
ContextAwareRunnable contextAwaretask = new ContextAwareRunnable(task);
Subject newsubject = new Subject.Builder().buildSubject();
newsubject.login(new RootAuthenticationToken());
try {
newsubject.execute(contextAwaretask);
} finally {
newsubject.logout();
}
} | java |
public static ExecutorService getSecurityContextAwareExecutor(ExecutorService original) {
SubjectAwareExecutorService subjectAwareExecutor = new SubjectAwareExecutorService(original);
return ThreadLocalUtil.contextAwareExecutor(subjectAwareExecutor);
} | java |
public static <BeanType> BeanType createBeanFromAttributeMap(Class<BeanType> beanType,
Map<String, ? extends Object> attributeValues) {
BeanType instance;
try {
instance = beanType.newInstance();
BeanUtils.populate(instance, attributeValues);
} catch (Exception e) {
ReflectionUtils.handleReflectionException(e);
throw new IllegalStateException("Should never get here");
}
return instance;
} | java |
public synchronized void reloadRulebase() throws RuleBaseException {
long start = System.currentTimeMillis();
reloadDeclarations();
packageStrings.clear();
for (RuleBaseElementId id : manager.listAll(RuleBaseElementType.Function)) {
String packageName = id.getPackageName();
StringBuffer packageString = getPackageString(packageName);
String code = manager.get(id);
packageString.append(code);
}
for (RuleBaseElementId id : manager.listAll(RuleBaseElementType.Rule)) {
String packageName = id.getPackageName();
StringBuffer packageString = getPackageString(packageName);
String code = manager.get(id);
String formattedRule = String.format(RULE_TEMPLATE, id.getName(), code);
packageString.append(formattedRule);
}
for (RuleBaseElementId id : manager.listAll(RuleBaseElementType.Process)) {
getPackageString(id.getPackageName());
}
Collection<KnowledgePackage> compiledPackages = new HashSet<KnowledgePackage>();
if (packageStrings.isEmpty()) {
Set<String> emptySet = Collections.emptySet();
compiledPackages.addAll(compileDrlString("package dummy;\n" + declarations, emptySet));
} else {
for (Map.Entry<String, StringBuffer> entry : packageStrings.entrySet()) {
String packageName = entry.getKey();
StringBuffer drlCode = entry.getValue();
Collection<String> flows = queryFlows(packageName);
Collection<KnowledgePackage> compiledDrlPackage = compileDrlString(drlCode.toString(), flows);
compiledPackages.addAll(compiledDrlPackage);
}
}
lockRuleBase();
clearRulebase();
base.addKnowledgePackages(compiledPackages);
unlockRuleBase();
LOGGER.info("Reloading the rulebase took {}ms", System.currentTimeMillis() - start);
} | java |
@SuppressWarnings("unchecked")
public <T> T convertEDBObjectToModel(Class<T> model, EDBObject object) {
return (T) convertEDBObjectToUncheckedModel(model, object);
} | java |
public <T> List<T> convertEDBObjectsToModelObjects(Class<T> model, List<EDBObject> objects) {
List<T> models = new ArrayList<>();
for (EDBObject object : objects) {
T instance = convertEDBObjectToModel(model, object);
if (instance != null) {
models.add(instance);
}
}
return models;
} | java |
private boolean checkEDBObjectModelType(EDBObject object, Class<?> model) {
String modelClass = object.getString(EDBConstants.MODEL_TYPE);
if (modelClass == null) {
LOGGER.warn(String.format("The EDBObject with the oid %s has no model type information."
+ "The resulting model may be a different model type than expected.", object.getOID()));
}
if (modelClass != null && !modelClass.equals(model.getName())) {
return false;
}
return true;
} | java |
private Object convertEDBObjectToUncheckedModel(Class<?> model, EDBObject object) {
if (!checkEDBObjectModelType(object, model)) {
return null;
}
filterEngineeringObjectInformation(object, model);
List<OpenEngSBModelEntry> entries = new ArrayList<>();
for (PropertyDescriptor propertyDescriptor : getPropertyDescriptorsForClass(model)) {
if (propertyDescriptor.getWriteMethod() == null
|| propertyDescriptor.getName().equals(ModelUtils.MODEL_TAIL_FIELD_NAME)) {
continue;
}
Object value = getValueForProperty(propertyDescriptor, object);
Class<?> propertyClass = propertyDescriptor.getPropertyType();
if (propertyClass.isPrimitive()) {
entries.add(new OpenEngSBModelEntry(propertyDescriptor.getName(), value, ClassUtils
.primitiveToWrapper(propertyClass)));
} else {
entries.add(new OpenEngSBModelEntry(propertyDescriptor.getName(), value, propertyClass));
}
}
for (Map.Entry<String, EDBObjectEntry> objectEntry : object.entrySet()) {
EDBObjectEntry entry = objectEntry.getValue();
Class<?> entryType;
try {
entryType = model.getClassLoader().loadClass(entry.getType());
entries.add(new OpenEngSBModelEntry(entry.getKey(), entry.getValue(), entryType));
} catch (ClassNotFoundException e) {
LOGGER.error("Unable to load class {} of the model tail", entry.getType());
}
}
return ModelUtils.createModel(model, entries);
} | java |
private List<PropertyDescriptor> getPropertyDescriptorsForClass(Class<?> clasz) {
try {
BeanInfo beanInfo = Introspector.getBeanInfo(clasz);
return Arrays.asList(beanInfo.getPropertyDescriptors());
} catch (IntrospectionException e) {
LOGGER.error("instantiation exception while trying to create instance of class {}", clasz.getName());
}
return Lists.newArrayList();
} | java |
private Object getValueForProperty(PropertyDescriptor propertyDescriptor, EDBObject object) {
Method setterMethod = propertyDescriptor.getWriteMethod();
String propertyName = propertyDescriptor.getName();
Object value = object.getObject(propertyName);
Class<?> parameterType = setterMethod.getParameterTypes()[0];
// TODO: OPENENGSB-2719 do that in a better way than just an if-else series
if (Map.class.isAssignableFrom(parameterType)) {
List<Class<?>> classes = getGenericMapParameterClasses(setterMethod);
value = getMapValue(classes.get(0), classes.get(1), propertyName, object);
} else if (List.class.isAssignableFrom(parameterType)) {
Class<?> clazz = getGenericListParameterClass(setterMethod);
value = getListValue(clazz, propertyName, object);
} else if (parameterType.isArray()) {
Class<?> clazz = parameterType.getComponentType();
value = getArrayValue(clazz, propertyName, object);
} else if (value == null) {
return null;
} else if (OpenEngSBModel.class.isAssignableFrom(parameterType)) {
Object timestamp = object.getObject(EDBConstants.MODEL_TIMESTAMP);
Long time = System.currentTimeMillis();
if (timestamp != null) {
try {
time = Long.parseLong(timestamp.toString());
} catch (NumberFormatException e) {
LOGGER.warn("The model with the oid {} has an invalid timestamp.", object.getOID());
}
}
EDBObject obj = edbService.getObject((String) value, time);
value = convertEDBObjectToUncheckedModel(parameterType, obj);
object.remove(propertyName);
} else if (parameterType.equals(FileWrapper.class)) {
FileWrapper wrapper = new FileWrapper();
String filename = object.getString(propertyName + FILEWRAPPER_FILENAME_SUFFIX);
String content = (String) value;
wrapper.setFilename(filename);
wrapper.setContent(Base64.decodeBase64(content));
value = wrapper;
object.remove(propertyName + FILEWRAPPER_FILENAME_SUFFIX);
} else if (parameterType.equals(File.class)) {
return null;
} else if (object.containsKey(propertyName)) {
if (parameterType.isEnum()) {
value = getEnumValue(parameterType, value);
}
}
object.remove(propertyName);
return value;
} | java |
@SuppressWarnings("unchecked")
private <T> List<T> getListValue(Class<T> type, String propertyName, EDBObject object) {
List<T> temp = new ArrayList<>();
for (int i = 0;; i++) {
String property = getEntryNameForList(propertyName, i);
Object obj = object.getObject(property);
if (obj == null) {
break;
}
if (OpenEngSBModel.class.isAssignableFrom(type)) {
obj = convertEDBObjectToUncheckedModel(type, edbService.getObject(object.getString(property)));
}
temp.add((T) obj);
object.remove(property);
}
return temp;
} | java |
@SuppressWarnings("unchecked")
private <T> T[] getArrayValue(Class<T> type, String propertyName, EDBObject object) {
List<T> elements = getListValue(type, propertyName, object);
T[] ar = (T[]) Array.newInstance(type, elements.size());
return elements.toArray(ar);
} | java |
private Object getMapValue(Class<?> keyType, Class<?> valueType, String propertyName, EDBObject object) {
Map<Object, Object> temp = new HashMap<>();
for (int i = 0;; i++) {
String keyProperty = getEntryNameForMapKey(propertyName, i);
String valueProperty = getEntryNameForMapValue(propertyName, i);
if (!object.containsKey(keyProperty)) {
break;
}
Object key = object.getObject(keyProperty);
Object value = object.getObject(valueProperty);
if (OpenEngSBModel.class.isAssignableFrom(keyType)) {
key = convertEDBObjectToUncheckedModel(keyType, edbService.getObject(key.toString()));
}
if (OpenEngSBModel.class.isAssignableFrom(valueType)) {
value = convertEDBObjectToUncheckedModel(valueType, edbService.getObject(value.toString()));
}
temp.put(key, value);
object.remove(keyProperty);
object.remove(valueProperty);
}
return temp;
} | java |
private Object getEnumValue(Class<?> type, Object value) {
Object[] enumValues = type.getEnumConstants();
for (Object enumValue : enumValues) {
if (enumValue.toString().equals(value.toString())) {
value = enumValue;
break;
}
}
return value;
} | java |
public ConvertedCommit convertEKBCommit(EKBCommit commit) {
ConvertedCommit result = new ConvertedCommit();
ConnectorInformation information = commit.getConnectorInformation();
result.setInserts(convertModelsToEDBObjects(commit.getInserts(), information));
result.setUpdates(convertModelsToEDBObjects(commit.getUpdates(), information));
result.setDeletes(convertModelsToEDBObjects(commit.getDeletes(), information));
return result;
} | java |
private void fillEDBObjectWithEngineeringObjectInformation(EDBObject object, OpenEngSBModel model)
throws IllegalAccessException {
if (!new AdvancedModelWrapper(model).isEngineeringObject()) {
return;
}
for (Field field : model.getClass().getDeclaredFields()) {
OpenEngSBForeignKey annotation = field.getAnnotation(OpenEngSBForeignKey.class);
if (annotation == null) {
continue;
}
String value = (String) FieldUtils.readField(field, model, true);
if (value == null) {
continue;
}
value = String.format("%s/%s", ContextHolder.get().getCurrentContextId(), value);
String key = getEOReferenceStringFromAnnotation(annotation);
object.put(key, new EDBObjectEntry(key, value, String.class));
}
} | java |
private void filterEngineeringObjectInformation(EDBObject object, Class<?> model) {
if (!AdvancedModelWrapper.isEngineeringObjectClass(model)) {
return;
}
Iterator<String> keys = object.keySet().iterator();
while (keys.hasNext()) {
if (keys.next().startsWith(REFERENCE_PREFIX)) {
keys.remove();
}
}
} | java |
public static String getEntryNameForMapKey(String property, Integer index) {
return getEntryNameForMap(property, true, index);
} | java |
public static String getEntryNameForMapValue(String property, Integer index) {
return getEntryNameForMap(property, false, index);
} | java |
private static String getEntryNameForMap(String property, Boolean key, Integer index) {
return String.format("%s.%d.%s", property, index, key ? "key" : "value");
} | java |
public static String getEntryNameForList(String property, Integer index) {
return String.format("%s.%d", property, index);
} | java |
public static String getEOReferenceStringFromAnnotation(OpenEngSBForeignKey key) {
return String.format("%s%s:%s", REFERENCE_PREFIX, key.modelType(), key.modelVersion().toString());
} | java |
private static Map<String, ModelDescription> assigneModelsToViews(Map<ModelDescription,
XLinkConnectorView[]> modelsToViews) {
HashMap<String, ModelDescription> viewsToModels = new HashMap<String, ModelDescription>();
for (ModelDescription modelInfo : modelsToViews.keySet()) {
List<XLinkConnectorView> currentViewList = Arrays.asList(modelsToViews.get(modelInfo));
for (XLinkConnectorView view : currentViewList) {
if (!viewsToModels.containsKey(view.getViewId())) {
viewsToModels.put(view.getViewId(), modelInfo);
}
}
}
return viewsToModels;
} | java |
private static String getExpirationDate(int futureDays) {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_YEAR, futureDays);
Format formatter = new SimpleDateFormat(XLinkConstants.DATEFORMAT);
return formatter.format(calendar.getTime());
} | java |
public static void setValueOfModel(Object model, OpenEngSBModelEntry entry, Object value) throws
NoSuchFieldException,
IllegalArgumentException,
IllegalAccessException {
Class clazz = model.getClass();
Field field = clazz.getDeclaredField(entry.getKey());
field.setAccessible(true);
field.set(model, value);
} | java |
public static Object createInstanceOfModelClass(Class clazzObject,
List<OpenEngSBModelEntry> entries) {
return ModelUtils.createModel(clazzObject, entries);
} | java |
public static Calendar dateStringToCalendar(String dateString) {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat(XLinkConstants.DATEFORMAT);
try {
calendar.setTime(formatter.parse(dateString));
} catch (Exception ex) {
return null;
}
return calendar;
} | java |
private static String urlEncodeParameter(String parameter) {
try {
return URLEncoder.encode(parameter, "UTF-8");
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(XLinkUtils.class.getName()).log(Level.SEVERE, null, ex);
}
return parameter;
} | java |
public static XLinkConnectorView[] getViewsOfRegistration(XLinkConnectorRegistration registration) {
List<XLinkConnectorView> viewsOfRegistration = new ArrayList<XLinkConnectorView>();
Map<ModelDescription, XLinkConnectorView[]> modelsToViews = registration.getModelsToViews();
for (XLinkConnectorView[] views : modelsToViews.values()) {
for (int i = 0; i < views.length; i++) {
XLinkConnectorView view = views[i];
if (!viewsOfRegistration.contains(view)) {
viewsOfRegistration.add(view);
}
}
}
return viewsOfRegistration.toArray(new XLinkConnectorView[0]);
} | java |
public static XLinkConnector[] getLocalToolFromRegistrations(List<XLinkConnectorRegistration> registrations) {
List<XLinkConnector> tools = new ArrayList<XLinkConnector>();
for (XLinkConnectorRegistration registration : registrations) {
XLinkConnector newLocalTools
= new XLinkConnector(
registration.getConnectorId(),
registration.getToolName(),
getViewsOfRegistration(registration));
tools.add(newLocalTools);
}
return tools.toArray(new XLinkConnector[0]);
} | java |
private void mergeInTransaction(EntityManager em, Collection objects) {
EntityTransaction tx = null;
try {
tx = em.getTransaction();
tx.begin();
for (Object o : objects) {
em.merge(o);
}
tx.commit();
}
catch (RuntimeException e) {
if (tx != null && tx.isActive()) {
tx.rollback();
}
throw e;
}
} | java |
public void execute() {
try {
new JdbcTemplate(dataSource).execute(readResourceContent(SCHEMA_FILE)); // TODO: sql independence
} catch (IOException e) {
throw new RuntimeException("Could not create schema for EDBI Index", e);
}
} | java |
public static void addId(Entry entry, boolean updateRdn) {
String uuid = newUUID().toString();
try {
entry.add(SchemaConstants.OBJECT_CLASS_ATTRIBUTE, UNIQUE_OBJECT_OC);
entry.add(ID_ATTRIBUTE, uuid);
} catch (LdapException e) {
throw new LdapRuntimeException(e);
}
if (updateRdn) {
Dn newDn = LdapUtils.concatDn(ID_ATTRIBUTE, uuid, entry.getDn().getParent());
entry.setDn(newDn);
}
} | java |
public static void addIds(List<Entry> entries, boolean updateRdn) {
for (Entry entry : entries) {
addId(entry, updateRdn);
}
} | java |
protected synchronized void initialize() {
String invocationServiceName = this.invocationServiceName;
invocationService = (InvocationService)
CacheFactory.getService(invocationServiceName);
if (invocationService == null) {
throw new IllegalArgumentException("Invocation service ["
+ invocationServiceName
+ "] is not defined.");
}
invocationService.addMemberListener(this);
serviceMembers = invocationService.getInfo().getServiceMembers();
memberIterator = serviceMembers.iterator();
} | java |
public void execute(Runnable command) {
if (!(command instanceof ClusteredFutureTask)) {
command = new ClusteredFutureTask<Object>(command, null);
}
command.run();
} | java |
protected synchronized Member getExecutionMember() {
Iterator<Member> it = memberIterator;
if (it == null || !it.hasNext()) {
memberIterator = it = serviceMembers.iterator();
}
return it.next();
} | java |
protected BrokerServiceAccessor getMethodAccessor(String serviceBrokerName, CatalogService description) {
return new AnnotationBrokerServiceAccessor(description, serviceBrokerName, getBeanClass(serviceBrokerName),
context.getBean(serviceBrokerName));
} | java |
protected Class<?> getBeanClass(String beanName) {
Class<?> clazz = context.getType(beanName);
while (Proxy.isProxyClass(clazz) || Enhancer.isEnhanced(clazz)) {
clazz = clazz.getSuperclass();
}
return clazz;
} | java |
public void skipSolver(ConstraintSolver ... solvers) {
if (solversToSkip == null) solversToSkip = new HashSet<ConstraintSolver>();
for (ConstraintSolver solver : solvers) solversToSkip.add(solver);
} | java |
private void initAttributesAndElements(String... propertyNames)
{
for (String propertyName : propertyNames)
{
Property property = new Property(propertyName);
if (property.isAttribute())
{
m_attributes.add(property);
}
else
{
m_elements.add(property);
}
}
} | java |
public void setUsed(boolean newVal){
if(isUsed() && newVal == false) {
Arrays.fill(out, null);
}
used = newVal;
} | java |
private Character getPadCharacter(String characterString) {
if (characterString.length() > 0) {
getLogger().debug("The given character string is longer than one element. The first character is used.");
}
return characterString.charAt(0);
} | java |
private String getDirectionString(String direction) {
if (direction == null || !(direction.equals("Start") || direction.equals("End"))) {
getLogger().debug("Unrecognized direction string. The standard value 'Start' will be used.");
return "Start";
}
return direction;
} | java |
private String performPadOperation(String source, Integer length, Character padChar, String direction) {
if (direction.equals("Start")) {
return Strings.padStart(source, length, padChar);
} else {
return Strings.padEnd(source, length, padChar);
}
} | java |
public List<Project> findAllProjects() {
List<Project> list = new ArrayList<>();
List<String> projectNames;
try {
projectNames = readLines(projectsFile);
} catch (IOException e) {
throw new FileBasedRuntimeException(e);
}
for (String projectName : projectNames) {
if (StringUtils.isNotBlank(projectName)) {
list.add(new Project(projectName));
}
}
return list;
} | java |
public static Map<String, Class<?>> getPropertyTypeMap(Class<?> clazz, String... exclude) {
PropertyDescriptor[] descriptors;
try {
descriptors = getPropertyDescriptors(clazz);
} catch (IntrospectionException e) {
LOG.error("Failed to introspect " + clazz, e);
return Collections.emptyMap();
}
HashMap<String, Class<?>> map = new HashMap<>(descriptors.length);
for (PropertyDescriptor pd : descriptors) {
map.put(pd.getName(), pd.getPropertyType());
}
for (String property : exclude) {
map.remove(property);
}
return map;
} | java |
public static Map<String, Object> read(Object object) {
PropertyDescriptor[] descriptors;
Class<?> clazz = object.getClass();
try {
descriptors = getPropertyDescriptors(clazz);
} catch (IntrospectionException e) {
LOG.error("Failed to introspect " + clazz, e);
return Collections.emptyMap();
}
HashMap<String, Object> map = new HashMap<>(descriptors.length);
for (PropertyDescriptor pd : descriptors) {
try {
Object value = pd.getReadMethod().invoke(object);
map.put(pd.getName(), value);
} catch (IllegalAccessException | InvocationTargetException | IllegalArgumentException e) {
LOG.error("Failed to visit property " + pd.getName(), e);
}
}
map.remove("class");
return map;
} | java |
public static AdvancedModelWrapper wrap(Object model) {
if (!(isModel(model.getClass()))) {
throw new IllegalArgumentException("The given object is no model");
}
return new AdvancedModelWrapper((OpenEngSBModel) model);
} | java |
public List<EDBObject> getModelsReferringToThisModel(EngineeringDatabaseService edbService) {
return edbService.query(QueryRequest.query(
EDBConverter.REFERENCE_PREFIX + "%", getCompleteModelOID()));
} | java |
public static Boolean isEngineeringObjectClass(Class<?> clazz) {
for (Field field : clazz.getDeclaredFields()) {
if (field.isAnnotationPresent(OpenEngSBForeignKey.class)) {
return true;
}
}
return false;
} | java |
public static <T> T convertObject(String json, Class<T> clazz) throws IOException {
try {
if (clazz.isAnnotationPresent(Model.class)) {
return MODEL_MAPPER.readValue(json, clazz);
}
return MAPPER.readValue(json, clazz);
} catch (IOException e) {
String error = String.format("Unable to parse given json '%s' into class '%s'.", json, clazz.getName());
LOGGER.error(error, e);
throw new IOException(error, e);
}
} | java |
public IndexCommit convert(EKBCommit ekbCommit) {
IndexCommit commit = new IndexCommit();
commit.setCommitId(ekbCommit.getRevisionNumber());
commit.setParentCommitId(ekbCommit.getParentRevisionNumber());
commit.setConnectorId(ekbCommit.getConnectorId());
commit.setDomainId(ekbCommit.getDomainId());
commit.setInstanceId(ekbCommit.getInstanceId());
commit.setTimestamp(new Date());
commit.setUser(getUser());
commit.setContextId(getContextId());
List<OpenEngSBModel> inserts = ekbCommit.getInserts();
List<OpenEngSBModel> updates = ekbCommit.getUpdates();
List<OpenEngSBModel> deletes = ekbCommit.getDeletes();
Set<Class<?>> modelClasses = extractTypes(inserts, updates, deletes);
commit.setModelClasses(modelClasses);
commit.setInserts(mapByClass(inserts));
commit.setUpdates(mapByClass(updates));
commit.setDeletes(mapByClass(deletes));
return commit;
} | java |
protected Map<Class<?>, List<OpenEngSBModel>> mapByClass(Collection<OpenEngSBModel> models) {
return group(models, new Function<OpenEngSBModel, Class<?>>() {
@Override
public Class<?> apply(OpenEngSBModel input) {
return input.getClass();
}
});
} | java |
public Catalog createCatalog() {
final List<CatalogService> services = new ArrayList<>();
for (BrokerServiceAccessor serviceAccessor : serviceAccessors) {
services.add(serviceAccessor.getServiceDescription());
}
return new Catalog(services);
} | java |
public BrokerServiceAccessor getServiceAccessor(String serviceId) {
for (BrokerServiceAccessor serviceAccessor : serviceAccessors) {
if (serviceId.equals(serviceAccessor.getServiceDescription().getId())) {
return serviceAccessor;
}
}
throw new NotFoundException("Could not find service broker with service_id " + serviceId);
} | java |
public static void setIdFieldValue(ODocument document, String value) {
setFieldValue(document, OGraphDatabase.LABEL, value);
} | java |
public static void setActiveFieldValue(ODocument document, Boolean active) {
setFieldValue(document, ACTIVE_FIELD, active.toString());
} | java |
public static String getFieldValue(ODocument document, String fieldname) {
return (String) document.field(fieldname);
} | java |
public static void setFieldValue(ODocument document, String fieldname, String value) {
document.field(fieldname, value);
} | java |
public static void fillEdgeWithPropertyConnections(ODocument edge, TransformationDescription description) {
Map<String, String> connections = convertPropertyConnectionsToSimpleForm(description.getPropertyConnections());
for (Map.Entry<String, String> entry : connections.entrySet()) {
edge.field(entry.getKey(), entry.getValue());
}
} | java |
public int[][] getVariations() {
int permutations = (int) Math.pow(n, r);
int[][] table = new int[permutations][r];
for (int x = 0; x < r; x++) {
int t2 = (int) Math.pow(n, x);
for (int p1 = 0; p1 < permutations;) {
for (int al = 0; al < n; al++) {
for (int p2 = 0; p2 < t2; p2++) {
table[p1][x] = al;
p1++;
}
}
}
}
return table;
} | java |
private List<JPAObject> checkInserts(List<JPAObject> inserts) {
List<JPAObject> failedObjects = new ArrayList<JPAObject>();
for (JPAObject insert : inserts) {
String oid = insert.getOID();
if (checkIfActiveOidExisting(oid)) {
failedObjects.add(insert);
} else {
insert.addEntry(new JPAEntry(EDBConstants.MODEL_VERSION, "1", Integer.class.getName(), insert));
}
}
return failedObjects;
} | java |
private List<String> checkDeletions(List<String> deletes) {
List<String> failedObjects = new ArrayList<String>();
for (String delete : deletes) {
if (!checkIfActiveOidExisting(delete)) {
failedObjects.add(delete);
}
}
return failedObjects;
} | java |
private List<JPAObject> checkUpdates(List<JPAObject> updates) throws EDBException {
List<JPAObject> failedObjects = new ArrayList<JPAObject>();
for (JPAObject update : updates) {
try {
Integer modelVersion = investigateVersionAndCheckForConflict(update);
modelVersion++;
update.removeEntry(EDBConstants.MODEL_VERSION);
update.addEntry(new JPAEntry(EDBConstants.MODEL_VERSION, modelVersion + "",
Integer.class.getName(), update));
} catch (EDBException e) {
failedObjects.add(update);
}
}
return failedObjects;
} | java |
private Integer investigateVersionAndCheckForConflict(JPAObject newObject) throws EDBException {
JPAEntry entry = newObject.getEntry(EDBConstants.MODEL_VERSION);
String oid = newObject.getOID();
Integer modelVersion = 0;
if (entry != null) {
modelVersion = Integer.parseInt(entry.getValue());
Integer currentVersion = dao.getVersionOfOid(oid);
if (!modelVersion.equals(currentVersion)) {
try {
checkForConflict(newObject);
} catch (EDBException e) {
LOGGER.info("conflict detected, user get informed");
throw new EDBException("conflict was detected. There is a newer version of the model with the oid "
+ oid + " saved.");
}
modelVersion = currentVersion;
}
} else {
modelVersion = dao.getVersionOfOid(oid);
}
return modelVersion;
} | java |
private void checkForConflict(JPAObject newObject) throws EDBException {
String oid = newObject.getOID();
JPAObject object = dao.getJPAObject(oid);
for (JPAEntry entry : newObject.getEntries()) {
if (entry.getKey().equals(EDBConstants.MODEL_VERSION)) {
continue;
}
JPAEntry rival = object.getEntry(entry.getKey());
String value = rival != null ? rival.getValue() : null;
if (value == null || !value.equals(entry.getValue())) {
LOGGER.debug("Conflict detected at key {} when comparing {} with {}", new Object[]{ entry.getKey(),
entry.getValue(), value == null ? "null" : value });
throw new EDBException("Conflict detected. Failure when comparing the values of the key "
+ entry.getKey());
}
}
} | java |
@Override
public void execute() throws MojoExecutionException {
checkParameters();
windowsModus = isWindows();
if (windowsModus) {
setWindowsVariables();
} else {
setLinuxVariables();
}
createDllFromWsdl();
} | java |
private void createDllFromWsdl() throws MojoExecutionException {
getLog().info("Execute WSDl to cs command");
wsdlCommand();
getLog().info("Execute cs to dll command");
cscCommand();
if (generateNugetPackage) {
if (isLinux()) {
throw new MojoExecutionException(
"At this point, mono and nuget does not work so well together."
+ "Please execute the plugin with nuget under Windows");
}
nugetLib = nugetFolder + "lib";
getLog().info("Create Nuget folder structure");
createNugetStructure();
getLog().info("Copy the dlls to the nuget structure");
copyFilesToNuget();
getLog().info("Generate " + namespace + " .nuspec");
generateNugetPackedFile();
getLog().info("Pack .nuspec to a nuget package");
nugetPackCommand();
}
} | java |
private void wsdlCommand() throws MojoExecutionException {
String cmd = findWsdlCommand();
int i = 0;
for (String location : wsdlLocations) {
String outputFilename = new File(outputDirectory, namespace + (i++)
+ ".cs").getAbsolutePath();
String[] command = new String[]{ cmd, serverParameter,
"/n:" + namespace, location, "/out:" + outputFilename };
ProcessBuilder builder = new ProcessBuilder();
builder.redirectErrorStream(true);
builder.command(command);
try {
executeACommand(builder.start());
} catch (IOException | InterruptedException e) {
throw new MojoExecutionException(
"Error, while executing command: "
+ Arrays.toString(command) + "\n", e);
}
cspath.add(outputFilename);
}
try {
FileComparer.removeSimilaritiesAndSaveFiles(cspath, getLog(),
windowsModus);
} catch (IOException e) {
throw new MojoExecutionException(
"It was not possible, to remove similarities form the files",
e);
}
} | java |
private void cscCommand() throws MojoExecutionException {
generateAssemblyInfo();
String cscPath = findCscCommand();
List<String> commandList = new LinkedList<String>(cspath);
commandList.add(0, cscPath);
commandList.add(1, "/target:library");
commandList.add(2, "/out:" + namespace + ".dll");
if (isLinux()) {
commandList.add(3, "/reference:System.Web.Services");
}
String[] command = commandList.toArray(new String[commandList.size()]);
ProcessBuilder builder = new ProcessBuilder();
builder.redirectErrorStream(true);
builder.directory(outputDirectory);
builder.command(command);
try {
executeACommand(builder.start());
} catch (InterruptedException | IOException e) {
throw new MojoExecutionException("Error, while executing command: "
+ Arrays.toString(command) + "\n", e);
}
} | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.