_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q9000
BaseServiceImp.fromJsonString
train
protected <T> T fromJsonString(String json, Class<T> clazz) { return _gsonParser.fromJson(json, clazz); }
java
{ "resource": "" }
q9001
LuaScriptBuilder.endScript
train
public LuaScript endScript(LuaScriptConfig config) { if (!endsWithReturnStatement()) { add(new LuaAstReturnStatement()); } String scriptText = buildScriptText(); return new BasicLuaScript(scriptText, config); }
java
{ "resource": "" }
q9002
LuaScriptBuilder.endScriptReturn
train
public LuaScript endScriptReturn(LuaValue value, LuaScriptConfig config) { add(new LuaAstReturnStatement(argument(value))); String scriptText = buildScriptText(); return new BasicLuaScript(scriptText, config); }
java
{ "resource": "" }
q9003
LuaScriptBuilder.endPreparedScript
train
public LuaPreparedScript endPreparedScript(LuaScriptConfig config) { if (!endsWithReturnStatement()) { add(new LuaAstReturnStatement()); } String scriptText = buildScriptText(); ArrayList<LuaKeyArgument> keyList = new ArrayList<>(keyArg2AstArg.keySet()); ArrayList<LuaValueArgument> argvList = new ArrayList<>(valueArg2AstArg.keySet()); if (config.isThreadSafe()) { return new ThreadSafeLuaPreparedScript(scriptText, keyList, argvList, config); } else { return new BasicLuaPreparedScript(scriptText, keyList, argvList, config); } }
java
{ "resource": "" }
q9004
LuaScriptBuilder.endPreparedScriptReturn
train
public LuaPreparedScript endPreparedScriptReturn(LuaValue value, LuaScriptConfig config) { add(new LuaAstReturnStatement(argument(value))); return endPreparedScript(config); }
java
{ "resource": "" }
q9005
EmbeddedPostgreSQLController.getCluster
train
private synchronized static Cluster getCluster(URI baseUrl, String[] personalities) throws IOException { final Entry<URI, Set<String>> key = Maps.immutableEntry(baseUrl, (Set<String>)ImmutableSet.copyOf(personalities)); Cluster result = CLUSTERS.get(key); if (result != null) { return result; } result = new Cluster(EmbeddedPostgreSQL.start()); final DBI dbi = new DBI(result.getPg().getTemplateDatabase()); final Migratory migratory = new Migratory(new MigratoryConfig() {}, dbi, dbi); migratory.addLocator(new DatabasePreparerLocator(migratory, baseUrl)); final MigrationPlan plan = new MigrationPlan(); int priority = 100; for (final String personality : personalities) { plan.addMigration(personality, Integer.MAX_VALUE, priority--); } migratory.dbMigrate(plan); result.start(); CLUSTERS.put(key, result); return result; }
java
{ "resource": "" }
q9006
EmbeddedPostgreSQLController.getConfigurationTweak
train
public ImmutableMap<String, String> getConfigurationTweak(String dbModuleName) { final DbInfo db = cluster.getNextDb(); return ImmutableMap.of("ness.db." + dbModuleName + ".uri", getJdbcUri(db), "ness.db." + dbModuleName + ".ds.user", db.user); }
java
{ "resource": "" }
q9007
JedisMap.remove
train
public long remove(final String... fields) { return doWithJedis(new JedisCallable<Long>() { @Override public Long call(Jedis jedis) { return jedis.hdel(getKey(), fields); } }); }
java
{ "resource": "" }
q9008
JedisSortedSet.score
train
public Double score(final String member) { return doWithJedis(new JedisCallable<Double>() { @Override public Double call(Jedis jedis) { return jedis.zscore(getKey(), member); } }); }
java
{ "resource": "" }
q9009
JedisSortedSet.add
train
public boolean add(final String member, final double score) { return doWithJedis(new JedisCallable<Boolean>() { @Override public Boolean call(Jedis jedis) { return jedis.zadd(getKey(), score, member) > 0; } }); }
java
{ "resource": "" }
q9010
JedisSortedSet.addAll
train
public long addAll(final Map<String, Double> scoredMember) { return doWithJedis(new JedisCallable<Long>() { @Override public Long call(Jedis jedis) { return jedis.zadd(getKey(), scoredMember); } }); }
java
{ "resource": "" }
q9011
JedisSortedSet.rangeByRank
train
public Set<String> rangeByRank(final long start, final long end) { return doWithJedis(new JedisCallable<Set<String>>() { @Override public Set<String> call(Jedis jedis) { return jedis.zrange(getKey(), start, end); } }); }
java
{ "resource": "" }
q9012
JedisSortedSet.rangeByRankReverse
train
public Set<String> rangeByRankReverse(final long start, final long end) { return doWithJedis(new JedisCallable<Set<String>>() { @Override public Set<String> call(Jedis jedis) { return jedis.zrevrange(getKey(), start, end); } }); }
java
{ "resource": "" }
q9013
JedisSortedSet.countByLex
train
public long countByLex(final LexRange lexRange) { return doWithJedis(new JedisCallable<Long>() { @Override public Long call(Jedis jedis) { return jedis.zlexcount(getKey(), lexRange.from(), lexRange.to()); } }); }
java
{ "resource": "" }
q9014
JedisSortedSet.rangeByLex
train
public Set<String> rangeByLex(final LexRange lexRange) { return doWithJedis(new JedisCallable<Set<String>>() { @Override public Set<String> call(Jedis jedis) { if (lexRange.hasLimit()) { return jedis.zrangeByLex(getKey(), lexRange.from(), lexRange.to(), lexRange.offset(), lexRange.count()); } else { return jedis.zrangeByLex(getKey(), lexRange.from(), lexRange.to()); } } }); }
java
{ "resource": "" }
q9015
JedisSortedSet.rangeByLexReverse
train
public Set<String> rangeByLexReverse(final LexRange lexRange) { return doWithJedis(new JedisCallable<Set<String>>() { @Override public Set<String> call(Jedis jedis) { if (lexRange.hasLimit()) { return jedis.zrevrangeByLex(getKey(), lexRange.fromReverse(), lexRange.toReverse(), lexRange.offset(), lexRange.count()); } else { return jedis.zrevrangeByLex(getKey(), lexRange.fromReverse(), lexRange.toReverse()); } } }); }
java
{ "resource": "" }
q9016
JedisSortedSet.removeRangeByLex
train
public long removeRangeByLex(final LexRange lexRange) { return doWithJedis(new JedisCallable<Long>() { @Override public Long call(Jedis jedis) { return jedis.zremrangeByLex(getKey(), lexRange.from(), lexRange.to()); } }); }
java
{ "resource": "" }
q9017
JedisSortedSet.rangeByScoreReverse
train
public Set<String> rangeByScoreReverse(final ScoreRange scoreRange) { return doWithJedis(new JedisCallable<Set<String>>() { @Override public Set<String> call(Jedis jedis) { if (scoreRange.hasLimit()) { return jedis.zrevrangeByScore(getKey(), scoreRange.fromReverse(), scoreRange.toReverse(), scoreRange.offset(), scoreRange.count()); } else { return jedis.zrevrangeByScore(getKey(), scoreRange.fromReverse(), scoreRange.toReverse()); } } }); }
java
{ "resource": "" }
q9018
JedisSortedSet.removeRangeByScore
train
public long removeRangeByScore(final ScoreRange scoreRange) { return doWithJedis(new JedisCallable<Long>() { @Override public Long call(Jedis jedis) { return jedis.zremrangeByScore(getKey(), scoreRange.from(), scoreRange.to()); } }); }
java
{ "resource": "" }
q9019
QuickHull3D.build
train
public void build(double[] coords, int nump) throws IllegalArgumentException { if (nump < 4) { throw new IllegalArgumentException("Less than four input points specified"); } if (coords.length / 3 < nump) { throw new IllegalArgumentException("Coordinate array too small for specified number of points"); } initBuffers(nump); setPoints(coords, nump); buildHull(); }
java
{ "resource": "" }
q9020
QuickHull3D.build
train
public void build(Point3d[] points, int nump) throws IllegalArgumentException { if (nump < 4) { throw new IllegalArgumentException("Less than four input points specified"); } if (points.length < nump) { throw new IllegalArgumentException("Point array too small for specified number of points"); } initBuffers(nump); setPoints(points, nump); buildHull(); }
java
{ "resource": "" }
q9021
QuickHull3D.getVertices
train
public Point3d[] getVertices() { Point3d[] vtxs = new Point3d[numVertices]; for (int i = 0; i < numVertices; i++) { vtxs[i] = pointBuffer[vertexPointIndices[i]].pnt; } return vtxs; }
java
{ "resource": "" }
q9022
QuickHull3D.getVertices
train
public int getVertices(double[] coords) { for (int i = 0; i < numVertices; i++) { Point3d pnt = pointBuffer[vertexPointIndices[i]].pnt; coords[i * 3 + 0] = pnt.x; coords[i * 3 + 1] = pnt.y; coords[i * 3 + 2] = pnt.z; } return numVertices; }
java
{ "resource": "" }
q9023
QuickHull3D.getVertexPointIndices
train
public int[] getVertexPointIndices() { int[] indices = new int[numVertices]; for (int i = 0; i < numVertices; i++) { indices[i] = vertexPointIndices[i]; } return indices; }
java
{ "resource": "" }
q9024
JedisSet.addAll
train
public long addAll(final String... members) { return doWithJedis(new JedisCallable<Long>() { @Override public Long call(Jedis jedis) { return jedis.sadd(getKey(), members); } }); }
java
{ "resource": "" }
q9025
JedisSet.removeAll
train
public long removeAll(final String... members) { return doWithJedis(new JedisCallable<Long>() { @Override public Long call(Jedis jedis) { return jedis.srem(getKey(), members); } }); }
java
{ "resource": "" }
q9026
JedisSet.pop
train
public String pop() { return doWithJedis(new JedisCallable<String>() { @Override public String call(Jedis jedis) { return jedis.spop(getKey()); } }); }
java
{ "resource": "" }
q9027
AbstractStore.idsOf
train
protected Object[] idsOf(final List<?> idsOrValues) { // convert list to array that we can mutate final Object[] ids = idsOrValues.toArray(); // mutate array to contain only non-empty ids int length = 0; for (int i = 0; i < ids.length;) { final Object p = ids[i++]; if (p instanceof HasId) { // only use values with ids that are non-empty final String id = ((HasId) p).getId(); if (!StringUtils.isEmpty(id)) { ids[length++] = id; } } else if (p instanceof String) { // only use ids that are non-empty final String id = p.toString(); if (!StringUtils.isEmpty(id)) { ids[length++] = id; } } else if (p != null) { throw new StoreException("Invalid id or value of type " + p); } } // no ids in array if (length == 0) { return null; } // some ids in array if (length != ids.length) { final Object[] tmp = new Object[length]; System.arraycopy(ids, 0, tmp, 0, length); return tmp; } // array was full return ids; }
java
{ "resource": "" }
q9028
JedisList.indexOf
train
public long indexOf(final String element) { return doWithJedis(new JedisCallable<Long>() { @Override public Long call(Jedis jedis) { return doIndexOf(jedis, element); } }); }
java
{ "resource": "" }
q9029
JedisList.get
train
public String get(final long index) { return doWithJedis(new JedisCallable<String>() { @Override public String call(Jedis jedis) { return jedis.lindex(getKey(), index); } }); }
java
{ "resource": "" }
q9030
JedisList.subList
train
public List<String> subList(final long fromIndex, final long toIndex) { return doWithJedis(new JedisCallable<List<String>>() { @Override public List<String> call(Jedis jedis) { return jedis.lrange(getKey(), fromIndex, toIndex); } }); }
java
{ "resource": "" }
q9031
JedisKeysScanner.ensureNext
train
private void ensureNext() { // Check if the current scan result has more keys (i.e. the index did not reach the end of the result list) if (resultIndex < scanResult.getResult().size()) { return; } // Since the current scan result was fully iterated, // if there is another cursor scan it and ensure next key (recursively) if (!FIRST_CURSOR.equals(scanResult.getStringCursor())) { scanResult = scan(scanResult.getStringCursor(), scanParams); resultIndex = 0; ensureNext(); } }
java
{ "resource": "" }
q9032
VertexList.addAll
train
public void addAll(Vertex vtx) { if (head == null) { head = vtx; } else { tail.next = vtx; } vtx.prev = tail; while (vtx.next != null) { vtx = vtx.next; } tail = vtx; }
java
{ "resource": "" }
q9033
VertexList.delete
train
public void delete(Vertex vtx) { if (vtx.prev == null) { head = vtx.next; } else { vtx.prev.next = vtx.next; } if (vtx.next == null) { tail = vtx.prev; } else { vtx.next.prev = vtx.prev; } }
java
{ "resource": "" }
q9034
VertexList.delete
train
public void delete(Vertex vtx1, Vertex vtx2) { if (vtx1.prev == null) { head = vtx2.next; } else { vtx1.prev.next = vtx2.next; } if (vtx2.next == null) { tail = vtx1.prev; } else { vtx2.next.prev = vtx1.prev; } }
java
{ "resource": "" }
q9035
VertexList.insertBefore
train
public void insertBefore(Vertex vtx, Vertex next) { vtx.prev = next.prev; if (next.prev == null) { head = vtx; } else { next.prev.next = vtx; } vtx.next = next; next.prev = vtx; }
java
{ "resource": "" }
q9036
Oracle9iLobHandler.freeTempLOB
train
private static void freeTempLOB(ClobWrapper clob, BlobWrapper blob) { try { if (clob != null) { // If the CLOB is open, close it if (clob.isOpen()) { clob.close(); } // Free the memory used by this CLOB clob.freeTemporary(); } if (blob != null) { // If the BLOB is open, close it if (blob.isOpen()) { blob.close(); } // Free the memory used by this BLOB blob.freeTemporary(); } } catch (Exception e) { logger.error("Error during temporary LOB release", e); } }
java
{ "resource": "" }
q9037
CollectionDescriptorConstraints.check
train
public void check(CollectionDescriptorDef collDef, String checkLevel) throws ConstraintException { ensureElementClassRef(collDef, checkLevel); checkInheritedForeignkey(collDef, checkLevel); ensureCollectionClass(collDef, checkLevel); checkProxyPrefetchingLimit(collDef, checkLevel); checkOrderby(collDef, checkLevel); checkQueryCustomizer(collDef, checkLevel); }
java
{ "resource": "" }
q9038
CollectionDescriptorConstraints.ensureElementClassRef
train
private void ensureElementClassRef(CollectionDescriptorDef collDef, String checkLevel) throws ConstraintException { if (CHECKLEVEL_NONE.equals(checkLevel)) { return; } String arrayElementClassName = collDef.getProperty(PropertyHelper.OJB_PROPERTY_ARRAY_ELEMENT_CLASS_REF); if (!collDef.hasProperty(PropertyHelper.OJB_PROPERTY_ELEMENT_CLASS_REF)) { if (arrayElementClassName != null) { // we use the array element type collDef.setProperty(PropertyHelper.OJB_PROPERTY_ELEMENT_CLASS_REF, arrayElementClassName); } else { throw new ConstraintException("Collection "+collDef.getName()+" in class "+collDef.getOwner().getName()+" does not specify its element class"); } } // now checking the element type ModelDef model = (ModelDef)collDef.getOwner().getOwner(); String elementClassName = collDef.getProperty(PropertyHelper.OJB_PROPERTY_ELEMENT_CLASS_REF); ClassDescriptorDef elementClassDef = model.getClass(elementClassName); if (elementClassDef == null) { throw new ConstraintException("Collection "+collDef.getName()+" in class "+collDef.getOwner().getName()+" references an unknown class "+elementClassName); } if (!elementClassDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_OJB_PERSISTENT, false)) { throw new ConstraintException("The element class "+elementClassName+" of the collection "+collDef.getName()+" in class "+collDef.getOwner().getName()+" is not persistent"); } if (CHECKLEVEL_STRICT.equals(checkLevel) && (arrayElementClassName != null)) { // specified element class must be a subtype of the element type try { InheritanceHelper helper = new InheritanceHelper(); if (!helper.isSameOrSubTypeOf(elementClassDef, arrayElementClassName, true)) { throw new ConstraintException("The element class "+elementClassName+" of the collection "+collDef.getName()+" in class "+collDef.getOwner().getName()+" is not the same or a subtype of the array base type "+arrayElementClassName); } } catch (ClassNotFoundException ex) { throw new ConstraintException("Could not find the class "+ex.getMessage()+" on the classpath while checking the collection "+collDef.getName()+" in class "+collDef.getOwner().getName()); } } // we're adjusting the property to use the classloader-compatible form collDef.setProperty(PropertyHelper.OJB_PROPERTY_ELEMENT_CLASS_REF, elementClassDef.getName()); }
java
{ "resource": "" }
q9039
CollectionDescriptorConstraints.ensureCollectionClass
train
private void ensureCollectionClass(CollectionDescriptorDef collDef, String checkLevel) throws ConstraintException { if (CHECKLEVEL_NONE.equals(checkLevel)) { return; } if (collDef.hasProperty(PropertyHelper.OJB_PROPERTY_ARRAY_ELEMENT_CLASS_REF)) { // an array cannot have a collection-class specified if (collDef.hasProperty(PropertyHelper.OJB_PROPERTY_COLLECTION_CLASS)) { throw new ConstraintException("Collection "+collDef.getName()+" in class "+collDef.getOwner().getName()+" is an array but does specify collection-class"); } else { // no further processing necessary as its an array return; } } if (CHECKLEVEL_STRICT.equals(checkLevel)) { InheritanceHelper helper = new InheritanceHelper(); ModelDef model = (ModelDef)collDef.getOwner().getOwner(); String specifiedClass = collDef.getProperty(PropertyHelper.OJB_PROPERTY_COLLECTION_CLASS); String variableType = collDef.getProperty(PropertyHelper.OJB_PROPERTY_VARIABLE_TYPE); try { if (specifiedClass != null) { // if we have a specified class then it has to implement the manageable collection and be a sub type of the variable type if (!helper.isSameOrSubTypeOf(specifiedClass, variableType)) { throw new ConstraintException("The type "+specifiedClass+" specified as collection-class of the collection "+collDef.getName()+" in class "+collDef.getOwner().getName()+" is not a sub type of the variable type "+variableType); } if (!helper.isSameOrSubTypeOf(specifiedClass, MANAGEABLE_COLLECTION_INTERFACE)) { throw new ConstraintException("The type "+specifiedClass+" specified as collection-class of the collection "+collDef.getName()+" in class "+collDef.getOwner().getName()+" does not implement "+MANAGEABLE_COLLECTION_INTERFACE); } } else { // no collection class specified so the variable type has to be a collection type if (helper.isSameOrSubTypeOf(variableType, MANAGEABLE_COLLECTION_INTERFACE)) { // we can specify it as a collection-class as it is an manageable collection collDef.setProperty(PropertyHelper.OJB_PROPERTY_COLLECTION_CLASS, variableType); } else if (!helper.isSameOrSubTypeOf(variableType, JAVA_COLLECTION_INTERFACE)) { throw new ConstraintException("The collection "+collDef.getName()+" in class "+collDef.getOwner().getName()+" needs the collection-class attribute as its variable type does not implement "+JAVA_COLLECTION_INTERFACE); } } } catch (ClassNotFoundException ex) { throw new ConstraintException("Could not find the class "+ex.getMessage()+" on the classpath while checking the collection "+collDef.getName()+" in class "+collDef.getOwner().getName()); } } }
java
{ "resource": "" }
q9040
CollectionDescriptorConstraints.checkOrderby
train
private void checkOrderby(CollectionDescriptorDef collDef, String checkLevel) throws ConstraintException { if (CHECKLEVEL_NONE.equals(checkLevel)) { return; } String orderbySpec = collDef.getProperty(PropertyHelper.OJB_PROPERTY_ORDERBY); if ((orderbySpec == null) || (orderbySpec.length() == 0)) { return; } ClassDescriptorDef ownerClass = (ClassDescriptorDef)collDef.getOwner(); String elementClassName = collDef.getProperty(PropertyHelper.OJB_PROPERTY_ELEMENT_CLASS_REF).replace('$', '.'); ClassDescriptorDef elementClass = ((ModelDef)ownerClass.getOwner()).getClass(elementClassName); FieldDescriptorDef fieldDef; String token; String fieldName; String ordering; int pos; for (CommaListIterator it = new CommaListIterator(orderbySpec); it.hasNext();) { token = it.getNext(); pos = token.indexOf('='); if (pos == -1) { fieldName = token; ordering = null; } else { fieldName = token.substring(0, pos); ordering = token.substring(pos + 1); } fieldDef = elementClass.getField(fieldName); if (fieldDef == null) { throw new ConstraintException("The field "+fieldName+" specified in the orderby attribute of the collection "+collDef.getName()+" in class "+ownerClass.getName()+" hasn't been found in the element class "+elementClass.getName()); } if ((ordering != null) && (ordering.length() > 0) && !"ASC".equals(ordering) && !"DESC".equals(ordering)) { throw new ConstraintException("The ordering "+ordering+" specified in the orderby attribute of the collection "+collDef.getName()+" in class "+ownerClass.getName()+" is invalid"); } } }
java
{ "resource": "" }
q9041
CollectionDescriptorConstraints.checkQueryCustomizer
train
private void checkQueryCustomizer(CollectionDescriptorDef collDef, String checkLevel) throws ConstraintException { if (!CHECKLEVEL_STRICT.equals(checkLevel)) { return; } String queryCustomizerName = collDef.getProperty(PropertyHelper.OJB_PROPERTY_QUERY_CUSTOMIZER); if (queryCustomizerName == null) { return; } try { InheritanceHelper helper = new InheritanceHelper(); if (!helper.isSameOrSubTypeOf(queryCustomizerName, QUERY_CUSTOMIZER_INTERFACE)) { throw new ConstraintException("The class "+queryCustomizerName+" specified as query-customizer of collection "+collDef.getName()+" in class "+collDef.getOwner().getName()+" does not implement the interface "+QUERY_CUSTOMIZER_INTERFACE); } } catch (ClassNotFoundException ex) { throw new ConstraintException("The class "+ex.getMessage()+" specified as query-customizer of collection "+collDef.getName()+" in class "+collDef.getOwner().getName()+" was not found on the classpath"); } }
java
{ "resource": "" }
q9042
ClassHelper.getClass
train
public static Class getClass(String className, boolean initialize) throws ClassNotFoundException { return Class.forName(className, initialize, getClassLoader()); }
java
{ "resource": "" }
q9043
ClassHelper.newInstance
train
public static Object newInstance(Class target, Class[] types, Object[] args) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { return newInstance(target, types, args, false); }
java
{ "resource": "" }
q9044
ClassHelper.getField
train
public static Field getField(Class clazz, String fieldName) { try { return clazz.getField(fieldName); } catch (Exception ignored) {} return null; }
java
{ "resource": "" }
q9045
ClassHelper.newInstance
train
public static Object newInstance(String className) throws InstantiationException, IllegalAccessException, ClassNotFoundException { return newInstance(getClass(className)); }
java
{ "resource": "" }
q9046
ClassHelper.newInstance
train
public static Object newInstance(String className, Class[] types, Object[] args) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, ClassNotFoundException { return newInstance(getClass(className), types, args); }
java
{ "resource": "" }
q9047
ClassHelper.newInstance
train
public static Object newInstance(Class target, Class type, Object arg) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { return newInstance(target, new Class[]{ type }, new Object[]{ arg }); }
java
{ "resource": "" }
q9048
ClassHelper.newInstance
train
public static Object newInstance(String className, Class type, Object arg) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, ClassNotFoundException { return newInstance(className, new Class[]{type}, new Object[]{arg}); }
java
{ "resource": "" }
q9049
ClassHelper.buildNewObjectInstance
train
public static Object buildNewObjectInstance(ClassDescriptor cld) { Object result = null; // If either the factory class and/or factory method is null, // just follow the normal code path and create via constructor if ((cld.getFactoryClass() == null) || (cld.getFactoryMethod() == null)) { try { // 1. create an empty Object (persistent classes need a public default constructor) Constructor con = cld.getZeroArgumentConstructor(); if(con == null) { throw new ClassNotPersistenceCapableException( "A zero argument constructor was not provided! Class was '" + cld.getClassNameOfObject() + "'"); } result = ConstructorHelper.instantiate(con); } catch (InstantiationException e) { throw new ClassNotPersistenceCapableException( "Can't instantiate class '" + cld.getClassNameOfObject()+"'"); } } else { try { // 1. create an empty Object by calling the no-parms factory method Method method = cld.getFactoryMethod(); if (Modifier.isStatic(method.getModifiers())) { // method is static so call it directly result = method.invoke(null, null); } else { // method is not static, so create an object of the factory first // note that this requires a public no-parameter (default) constructor Object factoryInstance = cld.getFactoryClass().newInstance(); result = method.invoke(factoryInstance, null); } } catch (Exception ex) { throw new PersistenceBrokerException("Unable to build object instance of class '" + cld.getClassNameOfObject() + "' from factory:" + cld.getFactoryClass() + "." + cld.getFactoryMethod(), ex); } } return result; }
java
{ "resource": "" }
q9050
StringContentTilePainter.createFeatureDocument
train
private GraphicsDocument createFeatureDocument(StringWriter writer) throws RenderException { if (TileMetadata.PARAM_SVG_RENDERER.equalsIgnoreCase(renderer)) { DefaultSvgDocument document = new DefaultSvgDocument(writer, false); document.setMaximumFractionDigits(MAXIMUM_FRACTION_DIGITS); document.registerWriter(InternalFeatureImpl.class, new SvgFeatureWriter(getTransformer())); document.registerWriter(InternalTileImpl.class, new SvgTileWriter()); return document; } else if (TileMetadata.PARAM_VML_RENDERER.equalsIgnoreCase(renderer)) { DefaultVmlDocument document = new DefaultVmlDocument(writer); int coordWidth = tile.getScreenWidth(); int coordHeight = tile.getScreenHeight(); document.registerWriter(InternalFeatureImpl.class, new VmlFeatureWriter(getTransformer(), coordWidth, coordHeight)); document.registerWriter(InternalTileImpl.class, new VmlTileWriter(coordWidth, coordHeight)); document.setMaximumFractionDigits(MAXIMUM_FRACTION_DIGITS); return document; } else { throw new RenderException(ExceptionCode.RENDERER_TYPE_NOT_SUPPORTED, renderer); } }
java
{ "resource": "" }
q9051
StringContentTilePainter.createLabelDocument
train
private GraphicsDocument createLabelDocument(StringWriter writer, LabelStyleInfo labelStyleInfo) throws RenderException { if (TileMetadata.PARAM_SVG_RENDERER.equalsIgnoreCase(renderer)) { DefaultSvgDocument document = new DefaultSvgDocument(writer, false); document.setMaximumFractionDigits(MAXIMUM_FRACTION_DIGITS); document.registerWriter(InternalTileImpl.class, new SvgLabelTileWriter(getTransformer(), labelStyleInfo, geoService, textService)); return document; } else if (TileMetadata.PARAM_VML_RENDERER.equalsIgnoreCase(renderer)) { DefaultVmlDocument document = new DefaultVmlDocument(writer); int coordWidth = tile.getScreenWidth(); int coordHeight = tile.getScreenHeight(); document.registerWriter(InternalFeatureImpl.class, new VmlFeatureWriter(getTransformer(), coordWidth, coordHeight)); document.registerWriter(InternalTileImpl.class, new VmlLabelTileWriter(coordWidth, coordHeight, getTransformer(), labelStyleInfo, geoService, textService)); document.setMaximumFractionDigits(MAXIMUM_FRACTION_DIGITS); return document; } else { throw new RenderException(ExceptionCode.RENDERER_TYPE_NOT_SUPPORTED, renderer); } }
java
{ "resource": "" }
q9052
StringContentTilePainter.getTransformer
train
private GeometryCoordinateSequenceTransformer getTransformer() { if (unitToPixel == null) { unitToPixel = new GeometryCoordinateSequenceTransformer(); unitToPixel.setMathTransform(ProjectiveTransform.create(new AffineTransform(scale, 0, 0, -scale, -scale * panOrigin.x, scale * panOrigin.y))); } return unitToPixel; }
java
{ "resource": "" }
q9053
PreparedStatementInvocationHandler.doExecute
train
private void doExecute(Connection conn) throws SQLException { PreparedStatement stmt; int size; size = _methods.size(); if ( size == 0 ) { return; } stmt = conn.prepareStatement(_sql); try { m_platform.afterStatementCreate(stmt); } catch ( PlatformException e ) { if ( e.getCause() instanceof SQLException ) { throw (SQLException)e.getCause(); } else { throw new SQLException(e.getMessage()); } } try { m_platform.beforeBatch(stmt); } catch ( PlatformException e ) { if ( e.getCause() instanceof SQLException ) { throw (SQLException)e.getCause(); } else { throw new SQLException(e.getMessage()); } } try { for ( int i = 0; i < size; i++ ) { Method method = (Method) _methods.get(i); try { if ( method.equals(ADD_BATCH) ) { /** * we invoke on the platform and pass the stmt as an arg. */ m_platform.addBatch(stmt); } else { method.invoke(stmt, (Object[]) _params.get(i)); } } catch (IllegalArgumentException ex) { StringBuffer buffer = generateExceptionMessage(i, stmt, ex); throw new SQLException(buffer.toString()); } catch ( IllegalAccessException ex ) { StringBuffer buffer = generateExceptionMessage(i, stmt, ex); throw new SQLException(buffer.toString()); } catch ( InvocationTargetException ex ) { Throwable th = ex.getTargetException(); if ( th == null ) { th = ex; } if ( th instanceof SQLException ) { throw ((SQLException) th); } else { throw new SQLException(th.toString()); } } catch (PlatformException e) { throw new SQLException(e.toString()); } } try { /** * this will call the platform specific call */ m_platform.executeBatch(stmt); } catch ( PlatformException e ) { if ( e.getCause() instanceof SQLException ) { throw (SQLException)e.getCause(); } else { throw new SQLException(e.getMessage()); } } } finally { stmt.close(); _methods.clear(); _params.clear(); } }
java
{ "resource": "" }
q9054
JadexAgentIntrospector.getBeliefValue
train
public Object getBeliefValue(String agent_name, final String belief_name, Connector connector) { ((IExternalAccess) connector.getAgentsExternalAccess(agent_name)) .scheduleStep(new IComponentStep<Integer>() { public IFuture<Integer> execute(IInternalAccess ia) { IBDIInternalAccess bia = (IBDIInternalAccess) ia; belief_value = bia.getBeliefbase() .getBelief(belief_name).getFact(); return null; } }).get(new ThreadSuspendable()); return belief_value; }
java
{ "resource": "" }
q9055
JadexAgentIntrospector.setBeliefValue
train
public void setBeliefValue(String agent_name, final String belief_name, final Object new_value, Connector connector) { ((IExternalAccess) connector.getAgentsExternalAccess(agent_name)) .scheduleStep(new IComponentStep<Integer>() { public IFuture<Integer> execute(IInternalAccess ia) { IBDIInternalAccess bia = (IBDIInternalAccess) ia; bia.getBeliefbase().getBelief(belief_name) .setFact(new_value); return null; } }).get(new ThreadSuspendable()); }
java
{ "resource": "" }
q9056
JadexAgentIntrospector.getAgentPlans
train
public IPlan[] getAgentPlans(final String agent_name, Connector connector) { ((IExternalAccess) connector.getAgentsExternalAccess(agent_name)) .scheduleStep(new IComponentStep<Plan>() { public IFuture<Plan> execute(IInternalAccess ia) { IBDIInternalAccess bia = (IBDIInternalAccess) ia; plans = bia.getPlanbase().getPlans(); return null; } }).get(new ThreadSuspendable()); return plans; }
java
{ "resource": "" }
q9057
JadexAgentIntrospector.getAgentGoals
train
public IGoal[] getAgentGoals(final String agent_name, Connector connector) { ((IExternalAccess) connector.getAgentsExternalAccess(agent_name)) .scheduleStep(new IComponentStep<Plan>() { public IFuture<Plan> execute(IInternalAccess ia) { IBDIInternalAccess bia = (IBDIInternalAccess) ia; goals = bia.getGoalbase().getGoals(); return null; } }).get(new ThreadSuspendable()); return goals; }
java
{ "resource": "" }
q9058
ConnectionManagerImpl.localBegin
train
public void localBegin() { if (this.isInLocalTransaction) { throw new TransactionInProgressException("Connection is already in transaction"); } Connection connection = null; try { connection = this.getConnection(); } catch (LookupException e) { /** * must throw to notify user that we couldn't start a connection */ throw new PersistenceBrokerException("Can't lookup a connection", e); } if (log.isDebugEnabled()) log.debug("localBegin was called for con " + connection); // change autoCommit state only if we are not in a managed environment // and it is enabled by user if(!broker.isManaged()) { if (jcd.getUseAutoCommit() == JdbcConnectionDescriptor.AUTO_COMMIT_SET_TRUE_AND_TEMPORARY_FALSE) { if (log.isDebugEnabled()) log.debug("Try to change autoCommit state to 'false'"); platform.changeAutoCommitState(jcd, connection, false); } } else { if(log.isDebugEnabled()) log.debug( "Found managed environment setting in PB, will skip Platform.changeAutoCommitState(...) call"); } this.isInLocalTransaction = true; }
java
{ "resource": "" }
q9059
ConnectionManagerImpl.localCommit
train
public void localCommit() { if (log.isDebugEnabled()) log.debug("commit was called"); if (!this.isInLocalTransaction) { throw new TransactionNotInProgressException("Not in transaction, call begin() before commit()"); } try { if(!broker.isManaged()) { if (batchCon != null) { batchCon.commit(); } else if (con != null) { con.commit(); } } else { if(log.isDebugEnabled()) log.debug( "Found managed environment setting in PB, will skip Connection.commit() call"); } } catch (SQLException e) { log.error("Commit on underlying connection failed, try to rollback connection", e); this.localRollback(); throw new TransactionAbortedException("Commit on connection failed", e); } finally { this.isInLocalTransaction = false; restoreAutoCommitState(); this.releaseConnection(); } }
java
{ "resource": "" }
q9060
ConnectionManagerImpl.localRollback
train
public void localRollback() { log.info("Rollback was called, do rollback on current connection " + con); if (!this.isInLocalTransaction) { throw new PersistenceBrokerException("Not in transaction, cannot abort"); } try { //truncate the local transaction this.isInLocalTransaction = false; if(!broker.isManaged()) { if (batchCon != null) { batchCon.rollback(); } else if (con != null && !con.isClosed()) { con.rollback(); } } else { if(log.isEnabledFor(Logger.INFO)) log.info( "Found managed environment setting in PB, will ignore rollback call on connection, this should be done by JTA"); } } catch (SQLException e) { log.error("Rollback on the underlying connection failed", e); } finally { try { restoreAutoCommitState(); } catch(OJBRuntimeException ignore) { // Ignore or log exception } releaseConnection(); } }
java
{ "resource": "" }
q9061
ConnectionManagerImpl.restoreAutoCommitState
train
protected void restoreAutoCommitState() { try { if(!broker.isManaged()) { if (jcd.getUseAutoCommit() == JdbcConnectionDescriptor.AUTO_COMMIT_SET_TRUE_AND_TEMPORARY_FALSE && originalAutoCommitState == true && con != null && !con.isClosed()) { platform.changeAutoCommitState(jcd, con, true); } } else { if(log.isDebugEnabled()) log.debug( "Found managed environment setting in PB, will skip Platform.changeAutoCommitState(...) call"); } } catch (SQLException e) { // should never be reached throw new OJBRuntimeException("Restore of connection autocommit state failed", e); } }
java
{ "resource": "" }
q9062
ConnectionManagerImpl.isAlive
train
public boolean isAlive(Connection conn) { try { return con != null ? !con.isClosed() : false; } catch (SQLException e) { log.error("IsAlive check failed, running connection was invalid!!", e); return false; } }
java
{ "resource": "" }
q9063
AgentRegistration.registerAgent
train
public static void registerAgent(Agent agent, String serviceName, String serviceType) throws FIPAException{ DFAgentDescription dfd = new DFAgentDescription(); ServiceDescription sd = new ServiceDescription(); sd.setType(serviceType); sd.setName(serviceName); //NOTE El serviceType es un string que define el tipo de servicio publicado en el DF por el Agente X. // He escogido crear nombres en clave en jade.common.Definitions para este campo. //NOTE El serviceName es el nombre efectivo del servicio. // Esto es lo que el usuario va a definir en MockConfiguration.DFNameService y no el tipo como estaba puesto. // sd.setType(agentType); // sd.setName(agent.getLocalName()); //Add services?? // Sets the agent description dfd.setName(agent.getAID()); dfd.addServices(sd); // Register the agent DFService.register(agent, dfd); }
java
{ "resource": "" }
q9064
InterceptorFactory.getInstance
train
public static InterceptorFactory getInstance() { if (instance == null) { instance = new InterceptorFactory(); OjbConfigurator.getInstance().configure(instance); } return instance; }
java
{ "resource": "" }
q9065
DropTargetHelper.registerDropPasteWorker
train
public void registerDropPasteWorker(DropPasteWorkerInterface worker) { this.dropPasteWorkerSet.add(worker); defaultDropTarget.setDefaultActions( defaultDropTarget.getDefaultActions() | worker.getAcceptableActions(defaultDropTarget.getComponent()) ); }
java
{ "resource": "" }
q9066
DropTargetHelper.removeDropPasteWorker
train
public void removeDropPasteWorker(DropPasteWorkerInterface worker) { this.dropPasteWorkerSet.remove(worker); java.util.Iterator it = this.dropPasteWorkerSet.iterator(); int newDefaultActions = 0; while (it.hasNext()) newDefaultActions |= ((DropPasteWorkerInterface)it.next()).getAcceptableActions(defaultDropTarget.getComponent()); defaultDropTarget.setDefaultActions(newDefaultActions); }
java
{ "resource": "" }
q9067
JsonUtils.serialize
train
public static String serialize(final Object obj) throws IOException { final ObjectMapper mapper = new ObjectMapper(); mapper.disable(MapperFeature.USE_GETTERS_AS_SETTERS); return mapper.writeValueAsString(obj); }
java
{ "resource": "" }
q9068
JsonUtils.unserializeOrganization
train
public static Organization unserializeOrganization(final String organization) throws IOException { final ObjectMapper mapper = new ObjectMapper(); mapper.disable(MapperFeature.USE_GETTERS_AS_SETTERS); return mapper.readValue(organization, Organization.class); }
java
{ "resource": "" }
q9069
JsonUtils.unserializeModule
train
public static Module unserializeModule(final String module) throws IOException { final ObjectMapper mapper = new ObjectMapper(); mapper.disable(MapperFeature.USE_GETTERS_AS_SETTERS); return mapper.readValue(module, Module.class); }
java
{ "resource": "" }
q9070
JsonUtils.unserializeBuildInfo
train
public static Map<String,String> unserializeBuildInfo(final String buildInfo) throws IOException { final ObjectMapper mapper = new ObjectMapper(); mapper.disable(MapperFeature.USE_GETTERS_AS_SETTERS); return mapper.readValue(buildInfo, new TypeReference<Map<String, Object>>(){}); }
java
{ "resource": "" }
q9071
ThreadScope.get
train
public Object get(String name, ObjectFactory<?> factory) { ThreadScopeContext context = ThreadScopeContextHolder.getContext(); Object result = context.getBean(name); if (null == result) { result = factory.getObject(); context.setBean(name, result); } return result; }
java
{ "resource": "" }
q9072
ThreadScope.remove
train
public Object remove(String name) { ThreadScopeContext context = ThreadScopeContextHolder.getContext(); return context.remove(name); }
java
{ "resource": "" }
q9073
JobLogger.addItemsHandled
train
public static void addItemsHandled(String handledItemsType, int handledItemsNumber) { JobLogger jobLogger = (JobLogger) getInstance(); if (jobLogger == null) { return; } jobLogger.addItemsHandledInstance(handledItemsType, handledItemsNumber); }
java
{ "resource": "" }
q9074
ConnectionFactoryDBCPImpl.getDataSource
train
protected DataSource getDataSource(JdbcConnectionDescriptor jcd) throws LookupException { final PBKey key = jcd.getPBKey(); DataSource ds = (DataSource) dsMap.get(key); if (ds == null) { // Found no pool for PBKey try { synchronized (poolSynch) { // Setup new object pool ObjectPool pool = setupPool(jcd); poolMap.put(key, pool); // Wrap the underlying object pool as DataSource ds = wrapAsDataSource(jcd, pool); dsMap.put(key, ds); } } catch (Exception e) { log.error("Could not setup DBCP DataSource for " + jcd, e); throw new LookupException(e); } } return ds; }
java
{ "resource": "" }
q9075
ConnectionFactoryDBCPImpl.setupPool
train
protected ObjectPool setupPool(JdbcConnectionDescriptor jcd) { log.info("Create new ObjectPool for DBCP connections:" + jcd); try { ClassHelper.newInstance(jcd.getDriver()); } catch (InstantiationException e) { log.fatal("Unable to instantiate the driver class: " + jcd.getDriver() + " in ConnectionFactoryDBCImpl!" , e); } catch (IllegalAccessException e) { log.fatal("IllegalAccessException while instantiating the driver class: " + jcd.getDriver() + " in ConnectionFactoryDBCImpl!" , e); } catch (ClassNotFoundException e) { log.fatal("Could not find the driver class : " + jcd.getDriver() + " in ConnectionFactoryDBCImpl!" , e); } // Get the configuration for the connection pool GenericObjectPool.Config conf = jcd.getConnectionPoolDescriptor().getObjectPoolConfig(); // Get the additional abandoned configuration AbandonedConfig ac = jcd.getConnectionPoolDescriptor().getAbandonedConfig(); // Create the ObjectPool that serves as the actual pool of connections. final ObjectPool connectionPool = createConnectionPool(conf, ac); // Create a DriverManager-based ConnectionFactory that // the connectionPool will use to create Connection instances final org.apache.commons.dbcp.ConnectionFactory connectionFactory; connectionFactory = createConnectionFactory(jcd); // Create PreparedStatement object pool (if any) KeyedObjectPoolFactory statementPoolFactory = createStatementPoolFactory(jcd); // Set validation query and auto-commit mode final String validationQuery; final boolean defaultAutoCommit; final boolean defaultReadOnly = false; validationQuery = jcd.getConnectionPoolDescriptor().getValidationQuery(); defaultAutoCommit = (jcd.getUseAutoCommit() != JdbcConnectionDescriptor.AUTO_COMMIT_SET_FALSE); // // Now we'll create the PoolableConnectionFactory, which wraps // the "real" Connections created by the ConnectionFactory with // the classes that implement the pooling functionality. // final PoolableConnectionFactory poolableConnectionFactory; poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool, statementPoolFactory, validationQuery, defaultReadOnly, defaultAutoCommit, ac); return poolableConnectionFactory.getPool(); }
java
{ "resource": "" }
q9076
ConnectionFactoryDBCPImpl.wrapAsDataSource
train
protected DataSource wrapAsDataSource(JdbcConnectionDescriptor jcd, ObjectPool connectionPool) { final boolean allowConnectionUnwrap; if (jcd == null) { allowConnectionUnwrap = false; } else { final Properties properties = jcd.getConnectionPoolDescriptor().getDbcpProperties(); final String allowConnectionUnwrapParam; allowConnectionUnwrapParam = properties.getProperty(PARAM_NAME_UNWRAP_ALLOWED); allowConnectionUnwrap = allowConnectionUnwrapParam != null && Boolean.valueOf(allowConnectionUnwrapParam).booleanValue(); } final PoolingDataSource dataSource; dataSource = new PoolingDataSource(connectionPool); dataSource.setAccessToUnderlyingConnectionAllowed(allowConnectionUnwrap); if(jcd != null) { final AbandonedConfig ac = jcd.getConnectionPoolDescriptor().getAbandonedConfig(); if (ac.getRemoveAbandoned() && ac.getLogAbandoned()) { final LoggerWrapperPrintWriter loggerPiggyBack; loggerPiggyBack = new LoggerWrapperPrintWriter(log, Logger.ERROR); dataSource.setLogWriter(loggerPiggyBack); } } return dataSource; }
java
{ "resource": "" }
q9077
SelectionCriteria.setAlias
train
public void setAlias(String alias) { m_alias = alias; String attributePath = (String)getAttribute(); boolean allPathsAliased = true; m_userAlias = new UserAlias(alias, attributePath, allPathsAliased); }
java
{ "resource": "" }
q9078
TimeBasedRollEnforcer.begin
train
final void begin() { if (this.properties.isDateRollEnforced()) { final Thread thread = new Thread(this, "Log4J Time-based File-roll Enforcer"); thread.setDaemon(true); thread.start(); this.threadRef = thread; } }
java
{ "resource": "" }
q9079
GetMapConfigurationCommand.securityClone
train
public Map<String, ClientWidgetInfo> securityClone(Map<String, ClientWidgetInfo> widgetInfo) { Map<String, ClientWidgetInfo> res = new HashMap<String, ClientWidgetInfo>(); for (Map.Entry<String, ClientWidgetInfo> entry : widgetInfo.entrySet()) { ClientWidgetInfo value = entry.getValue(); if (!(value instanceof ServerSideOnlyInfo)) { res.put(entry.getKey(), value); } } return res; }
java
{ "resource": "" }
q9080
GetMapConfigurationCommand.securityClone
train
public ClientLayerInfo securityClone(ClientLayerInfo original) { // the data is explicitly copied as this assures the security is considered when copying. if (null == original) { return null; } ClientLayerInfo client = null; String layerId = original.getServerLayerId(); if (securityContext.isLayerVisible(layerId)) { client = (ClientLayerInfo) SerializationUtils.clone(original); client.setWidgetInfo(securityClone(original.getWidgetInfo())); client.getLayerInfo().setExtraInfo(securityCloneLayerExtraInfo(original.getLayerInfo().getExtraInfo())); if (client instanceof ClientVectorLayerInfo) { ClientVectorLayerInfo vectorLayer = (ClientVectorLayerInfo) client; // set statuses vectorLayer.setCreatable(securityContext.isLayerCreateAuthorized(layerId)); vectorLayer.setUpdatable(securityContext.isLayerUpdateAuthorized(layerId)); vectorLayer.setDeletable(securityContext.isLayerDeleteAuthorized(layerId)); // filter feature info FeatureInfo featureInfo = vectorLayer.getFeatureInfo(); List<AttributeInfo> originalAttr = featureInfo.getAttributes(); List<AttributeInfo> filteredAttr = new ArrayList<AttributeInfo>(); featureInfo.setAttributes(filteredAttr); for (AttributeInfo ai : originalAttr) { if (securityContext.isAttributeReadable(layerId, null, ai.getName())) { filteredAttr.add(ai); } } } } return client; }
java
{ "resource": "" }
q9081
LoggingKeysHandler.getKeyValue
train
public String getKeyValue(String key){ String keyName = keysMap.get(key); if (keyName != null){ return keyName; } return ""; //key wasn't defined in keys properties file }
java
{ "resource": "" }
q9082
FileUtils.serialize
train
public static void serialize(final File folder, final String content, final String fileName) throws IOException { if (!folder.exists()) { folder.mkdirs(); } final File output = new File(folder, fileName); try ( final FileWriter writer = new FileWriter(output); ) { writer.write(content); writer.flush(); } catch (Exception e) { throw new IOException("Failed to serialize the notification in folder " + folder.getPath(), e); } }
java
{ "resource": "" }
q9083
FileUtils.read
train
public static String read(final File file) throws IOException { final StringBuilder sb = new StringBuilder(); try ( final FileReader fr = new FileReader(file); final BufferedReader br = new BufferedReader(fr); ) { String sCurrentLine; while ((sCurrentLine = br.readLine()) != null) { sb.append(sCurrentLine); } } return sb.toString(); }
java
{ "resource": "" }
q9084
FileUtils.getSize
train
public static Long getSize(final File file){ if ( file!=null && file.exists() ){ return file.length(); } return null; }
java
{ "resource": "" }
q9085
FileUtils.touch
train
public static void touch(final File folder , final String fileName) throws IOException { if(!folder.exists()){ folder.mkdirs(); } final File touchedFile = new File(folder, fileName); // The JVM will only 'touch' the file if you instantiate a // FileOutputStream instance for the file in question. // You don't actually write any data to the file through // the FileOutputStream. Just instantiate it and close it. try ( FileOutputStream doneFOS = new FileOutputStream(touchedFile); ) { // Touching the file } catch (FileNotFoundException e) { throw new FileNotFoundException("Failed to the find file." + e); } }
java
{ "resource": "" }
q9086
LicenseHandler.init
train
private void init(final List<DbLicense> licenses) { licensesRegexp.clear(); for (final DbLicense license : licenses) { if (license.getRegexp() == null || license.getRegexp().isEmpty()) { licensesRegexp.put(license.getName(), license); } else { licensesRegexp.put(license.getRegexp(), license); } } }
java
{ "resource": "" }
q9087
LicenseHandler.getLicense
train
public DbLicense getLicense(final String name) { final DbLicense license = repoHandler.getLicense(name); if (license == null) { throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND) .entity("License " + name + " does not exist.").build()); } return license; }
java
{ "resource": "" }
q9088
LicenseHandler.deleteLicense
train
public void deleteLicense(final String licName) { final DbLicense dbLicense = getLicense(licName); repoHandler.deleteLicense(dbLicense.getName()); final FiltersHolder filters = new FiltersHolder(); final LicenseIdFilter licenseIdFilter = new LicenseIdFilter(licName); filters.addFilter(licenseIdFilter); for (final DbArtifact artifact : repoHandler.getArtifacts(filters)) { repoHandler.removeLicenseFromArtifact(artifact, licName, this); } }
java
{ "resource": "" }
q9089
LicenseHandler.resolve
train
public DbLicense resolve(final String licenseId) { for (final Entry<String, DbLicense> regexp : licensesRegexp.entrySet()) { try { if (licenseId.matches(regexp.getKey())) { return regexp.getValue(); } } catch (PatternSyntaxException e) { LOG.error("Wrong pattern for the following license " + regexp.getValue().getName(), e); continue; } } if(LOG.isWarnEnabled()) { LOG.warn(String.format("No matching pattern for license %s", licenseId)); } return null; }
java
{ "resource": "" }
q9090
LicenseHandler.resolveLicenses
train
public Set<DbLicense> resolveLicenses(List<String> licStrings) { Set<DbLicense> result = new HashSet<>(); licStrings .stream() .map(this::getMatchingLicenses) .forEach(result::addAll); return result; }
java
{ "resource": "" }
q9091
LicenseHandler.verityLicenseIsConflictFree
train
private void verityLicenseIsConflictFree(final DbLicense newComer) { if(newComer.getRegexp() == null || newComer.getRegexp().isEmpty()) { return; } final DbLicense existing = repoHandler.getLicense(newComer.getName()); final List<DbLicense> licenses = repoHandler.getAllLicenses(); if(null == existing) { licenses.add(newComer); } else { existing.setRegexp(newComer.getRegexp()); } final Optional<Report> reportOp = ReportsRegistry.findById(MULTIPLE_LICENSE_MATCHING_STRINGS); if (reportOp.isPresent()) { final Report reportDef = reportOp.get(); ReportRequest reportRequest = new ReportRequest(); reportRequest.setReportId(reportDef.getId()); Map<String, String> params = new HashMap<>(); // // TODO: Make the organization come as an external parameter from the client side. // This may have impact on the UI, as when the user will update a license he will // have to specify which organization he's editing the license for (in case there // are more organizations defined in the collection). // params.put("organization", "Axway"); reportRequest.setParamValues(params); final RepositoryHandler wrapped = wrapperBuilder .start(repoHandler) .replaceGetMethod("getAllLicenses", licenses) .build(); final ReportExecution execution = reportDef.execute(wrapped, reportRequest); List<String[]> data = execution.getData(); final Optional<String[]> first = data .stream() .filter(strings -> strings[2].contains(newComer.getName())) .findFirst(); if(first.isPresent()) { final String[] strings = first.get(); final String message = String.format( "Pattern conflict for string entry %s matching multiple licenses: %s", strings[1], strings[2]); LOG.info(message); throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST) .entity(message) .build()); } else { if(!data.isEmpty() && !data.get(0)[2].isEmpty()) { LOG.info("There are remote conflicts between existing licenses and artifact strings"); } } } else { if(LOG.isWarnEnabled()) { LOG.warn(String.format("Cannot find report by id %s", MULTIPLE_LICENSE_MATCHING_STRINGS)); } } }
java
{ "resource": "" }
q9092
DependencyHandler.getModuleDependencies
train
public List<Dependency> getModuleDependencies(final String moduleId, final FiltersHolder filters){ final DbModule module = moduleHandler.getModule(moduleId); final DbOrganization organization = moduleHandler.getOrganization(module); filters.setCorporateFilter(new CorporateFilter(organization)); return getModuleDependencies(module, filters, 1, new ArrayList<String>()); }
java
{ "resource": "" }
q9093
DependencyHandler.getDependencyReport
train
public DependencyReport getDependencyReport(final String moduleId, final FiltersHolder filters) { final DbModule module = moduleHandler.getModule(moduleId); final DbOrganization organization = moduleHandler.getOrganization(module); filters.setCorporateFilter(new CorporateFilter(organization)); final DependencyReport report = new DependencyReport(moduleId); final List<String> done = new ArrayList<String>(); for(final DbModule submodule: DataUtils.getAllSubmodules(module)){ done.add(submodule.getId()); } addModuleToReport(report, module, filters, done, 1); return report; }
java
{ "resource": "" }
q9094
CompositeRoller.roll
train
public final boolean roll(final LoggingEvent loggingEvent) { for (int i = 0; i < this.fileRollables.length; i++) { if (this.fileRollables[i].roll(loggingEvent)) { return true; } } return false; }
java
{ "resource": "" }
q9095
GetVectorTileRequest.isPartOf
train
public boolean isPartOf(GetVectorTileRequest request) { if (Math.abs(request.scale - scale) > EQUALS_DELTA) { return false; } if (code != null ? !code.equals(request.code) : request.code != null) { return false; } if (crs != null ? !crs.equals(request.crs) : request.crs != null) { return false; } if (filter != null ? !filter.equals(request.filter) : request.filter != null) { return false; } if (panOrigin != null ? !panOrigin.equals(request.panOrigin) : request.panOrigin != null) { return false; } if (renderer != null ? !renderer.equals(request.renderer) : request.renderer != null) { return false; } if (styleInfo != null ? !styleInfo.equals(request.styleInfo) : request.styleInfo != null) { return false; } if (paintGeometries && !request.paintGeometries) { return false; } if (paintLabels && !request.paintLabels) { return false; } return true; }
java
{ "resource": "" }
q9096
DependencyCheckPostProcessor.checkPluginDependencies
train
@PostConstruct protected void checkPluginDependencies() throws GeomajasException { if ("true".equals(System.getProperty("skipPluginDependencyCheck"))) { return; } if (null == declaredPlugins) { return; } // start by going through all plug-ins to build a map of versions for plug-in keys // includes verification that each key is only used once Map<String, String> versions = new HashMap<String, String>(); for (PluginInfo plugin : declaredPlugins.values()) { String name = plugin.getVersion().getName(); String version = plugin.getVersion().getVersion(); // check for multiple plugin with same name but different versions (duplicates allowed for jar+source dep) if (null != version) { String otherVersion = versions.get(name); if (null != otherVersion) { if (!version.startsWith(EXPR_START)) { if (!otherVersion.startsWith(EXPR_START) && !otherVersion.equals(version)) { throw new GeomajasException(ExceptionCode.DEPENDENCY_CHECK_INVALID_DUPLICATE, name, version, versions.get(name)); } versions.put(name, version); } } else { versions.put(name, version); } } } // Check dependencies StringBuilder message = new StringBuilder(); String backendVersion = versions.get("Geomajas"); for (PluginInfo plugin : declaredPlugins.values()) { String name = plugin.getVersion().getName(); message.append(checkVersion(name, "Geomajas back-end", plugin.getBackendVersion(), backendVersion)); List<PluginVersionInfo> dependencies = plugin.getDependencies(); if (null != dependencies) { for (PluginVersionInfo dependency : plugin.getDependencies()) { String depName = dependency.getName(); message.append(checkVersion(name, depName, dependency.getVersion(), versions.get(depName))); } } dependencies = plugin.getOptionalDependencies(); if (null != dependencies) { for (PluginVersionInfo dependency : dependencies) { String depName = dependency.getName(); String availableVersion = versions.get(depName); if (null != availableVersion) { message.append(checkVersion(name, depName, dependency.getVersion(), versions.get(depName))); } } } } if (message.length() > 0) { throw new GeomajasException(ExceptionCode.DEPENDENCY_CHECK_FAILED, message.toString()); } recorder.record(GROUP, VALUE); }
java
{ "resource": "" }
q9097
DependencyCheckPostProcessor.checkVersion
train
String checkVersion(String pluginName, String dependency, String requestedVersion, String availableVersion) { if (null == availableVersion) { return "Dependency " + dependency + " not found for " + pluginName + ", version " + requestedVersion + " or higher needed.\n"; } if (requestedVersion.startsWith(EXPR_START) || availableVersion.startsWith(EXPR_START)) { return ""; } Version requested = new Version(requestedVersion); Version available = new Version(availableVersion); if (requested.getMajor() != available.getMajor()) { return "Dependency " + dependency + " is provided in a incompatible API version for plug-in " + pluginName + ", which requests version " + requestedVersion + ", but version " + availableVersion + " supplied.\n"; } if (requested.after(available)) { return "Dependency " + dependency + " too old for " + pluginName + ", version " + requestedVersion + " or higher needed, but version " + availableVersion + " supplied.\n"; } return ""; }
java
{ "resource": "" }
q9098
ClassDescriptorConstraints.check
train
public void check(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException { ensureNoTableInfoIfNoRepositoryInfo(classDef, checkLevel); checkModifications(classDef, checkLevel); checkExtents(classDef, checkLevel); ensureTableIfNecessary(classDef, checkLevel); checkFactoryClassAndMethod(classDef, checkLevel); checkInitializationMethod(classDef, checkLevel); checkPrimaryKey(classDef, checkLevel); checkProxyPrefetchingLimit(classDef, checkLevel); checkRowReader(classDef, checkLevel); checkObjectCache(classDef, checkLevel); checkProcedures(classDef, checkLevel); }
java
{ "resource": "" }
q9099
ClassDescriptorConstraints.ensureNoTableInfoIfNoRepositoryInfo
train
private void ensureNoTableInfoIfNoRepositoryInfo(ClassDescriptorDef classDef, String checkLevel) { if (!classDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_GENERATE_REPOSITORY_INFO, true)) { classDef.setProperty(PropertyHelper.OJB_PROPERTY_GENERATE_TABLE_INFO, "false"); } }
java
{ "resource": "" }