code
stringlengths
73
34.1k
label
stringclasses
1 value
protected boolean checkPackageLocators(String classPackageName) { if (packageLocators != null && !disablePackageLocatorsScanning && classPackageName.length() > 0 && (packageLocatorsBasePackage == null || classPackageName.startsWith(packageLocatorsBasePackage))) { for (String packageLocator : packageLocators) { String[] splitted = classPackageName.split("\\."); if (es.cenobit.struts2.json.util.StringUtils.contains(splitted, packageLocator, false)) return true; } } return false; }
java
private static List<Segment> parseSegments(String origPathStr) { String pathStr = origPathStr; if (!pathStr.startsWith("/")) { pathStr = pathStr + "/"; } List<Segment> result = new ArrayList<>(); for (String segmentStr : PATH_SPLITTER.split(pathStr)) { Matcher m = SEGMENT_PATTERN.matcher(segmentStr); if (!m.matches()) { throw new IllegalArgumentException("Bad aql path: " + origPathStr); } Segment segment = new Segment(); segment.attribute = m.group(1); segment.nodeId = m.groupCount() >= 3 ? m.group(3) : null; result.add(segment); } return result; }
java
okhttp3.Response get(String url, Map<String, Object> params) throws RequestException, LocalOperationException { String fullUrl = getFullUrl(url); okhttp3.Request request = new okhttp3.Request.Builder() .url(addUrlParams(fullUrl, toPayload(params))) .addHeader("Transloadit-Client", version) .build(); try { return httpClient.newCall(request).execute(); } catch (IOException e) { throw new RequestException(e); } }
java
okhttp3.Response delete(String url, Map<String, Object> params) throws RequestException, LocalOperationException { okhttp3.Request request = new okhttp3.Request.Builder() .url(getFullUrl(url)) .delete(getBody(toPayload(params), null)) .addHeader("Transloadit-Client", version) .build(); try { return httpClient.newCall(request).execute(); } catch (IOException e) { throw new RequestException(e); } }
java
private String getFullUrl(String url) { return url.startsWith("https://") || url.startsWith("http://") ? url : transloadit.getHostUrl() + url; }
java
private Map<String, String> toPayload(Map<String, Object> data) throws LocalOperationException { Map<String, Object> dataClone = new HashMap<String, Object>(data); dataClone.put("auth", getAuthData()); Map<String, String> payload = new HashMap<String, String>(); payload.put("params", jsonifyData(dataClone)); if (transloadit.shouldSignRequest) { payload.put("signature", getSignature(jsonifyData(dataClone))); } return payload; }
java
private String jsonifyData(Map<String, ? extends Object> data) { JSONObject jsonData = new JSONObject(data); return jsonData.toString(); }
java
private static String convertISO88591toUTF8(String value) { try { return new String(value.getBytes(CharEncoding.ISO_8859_1), CharEncoding.UTF_8); } catch (UnsupportedEncodingException ex) { // ignore and fallback to original encoding return value; } }
java
@Override public Result getResult() throws Exception { Result returnResult = result; // If we've chained to other Actions, we need to find the last result while (returnResult instanceof ActionChainResult) { ActionProxy aProxy = ((ActionChainResult) returnResult).getProxy(); if (aProxy != null) { Result proxyResult = aProxy.getInvocation().getResult(); if ((proxyResult != null) && (aProxy.getExecuteResult())) { returnResult = proxyResult; } else { break; } } else { break; } } return returnResult; }
java
private void executeResult() throws Exception { result = createResult(); String timerKey = "executeResult: " + getResultCode(); try { UtilTimerStack.push(timerKey); if (result != null) { result.execute(this); } else if (resultCode != null && !Action.NONE.equals(resultCode)) { throw new ConfigurationException("No result defined for action " + getAction().getClass().getName() + " and result " + getResultCode(), proxy.getConfig()); } else { if (LOG.isDebugEnabled()) { LOG.debug("No result returned for action " + getAction().getClass().getName() + " at " + proxy.getConfig().getLocation()); } } } finally { UtilTimerStack.pop(timerKey); } }
java
protected <C> C convert(Object object, Class<C> targetClass) { return this.mapper.convertValue(object, targetClass); }
java
protected final void sendObjectToSocket(Object objectToSend, WriteCallback cb) { Session sess = this.getSession(); if (sess != null) { String json; try { json = this.mapper.writeValueAsString(objectToSend); } catch (JsonProcessingException e) { throw new RuntimeException("Failed to serialize object", e); } sess.getRemote().sendString(json, cb); } }
java
public List<String> deviceTypes() { Integer count = json().size(DEVICE_FAMILIES); List<String> deviceTypes = new ArrayList<String>(count); for(int i = 0 ; i < count ; i++) { String familyNumber = json().stringValue(DEVICE_FAMILIES, i); if(familyNumber.equals("1")) deviceTypes.add("iPhone"); if(familyNumber.equals("2")) deviceTypes.add("iPad"); } return deviceTypes; }
java
public static boolean hasAnnotation(Method method, Class<? extends Annotation> annotation) { return !searchForAnnotation(method, annotation).isEmpty(); }
java
public static <T extends Annotation> List<T> searchForAnnotation(Method method, Class<T> annotation) { if (method == null) { return Lists.newArrayList(); } return searchClasses(method, annotation, method.getDeclaringClass()); }
java
public void addStep(String name, String robot, Map<String, Object> options){ steps.addStep(name, robot, options); }
java
void merge(Archetype flatParent, Archetype specialized) { expandAttributeNodes(specialized.getDefinition()); flattenCObject(RmPath.ROOT, null, flatParent.getDefinition(), specialized.getDefinition()); mergeOntologies(flatParent.getTerminology(), specialized.getTerminology()); if (flatParent.getAnnotations() != null) { if (specialized.getAnnotations() == null) { specialized.setAnnotations(new ResourceAnnotations()); } annotationsMerger.merge(flatParent.getAnnotations().getItems(), specialized.getAnnotations().getItems()); } }
java
public static void addTTLIndex(DBCollection collection, String field, int ttl) { if (ttl <= 0) { throw new IllegalArgumentException("TTL must be positive"); } collection.createIndex(new BasicDBObject(field, 1), new BasicDBObject("expireAfterSeconds", ttl)); }
java
public static void addIndex(DBCollection collection, String field, boolean asc, boolean background) { int dir = (asc) ? 1 : -1; collection.createIndex(new BasicDBObject(field, dir), new BasicDBObject("background", background)); }
java
void checkRmModelConformance() { final AmVisitor<AmObject, AmConstraintContext> visitor = AmVisitors.preorder(new ConformanceVisitor()); ArchetypeWalker.walkConstraints(visitor, archetype, new AmConstraintContext()); }
java
public static ResourceKey key(Enum<?> value) { return new ResourceKey(value.getClass().getName(), value.name()); }
java
public static ResourceKey key(Class<?> clazz, String id) { return new ResourceKey(clazz.getName(), id); }
java
public static ResourceKey key(Class<?> clazz, Enum<?> value) { return new ResourceKey(clazz.getName(), value.name()); }
java
public static ResourceKey key(Enum<?> enumValue, String key) { return new ResourceKey(enumValue.getClass().getName(), enumValue.name()).child(key); }
java
public void set(int i, double value) { switch (i) { case 0: { x = value; break; } case 1: { y = value; break; } case 2: { z = value; break; } default: { throw new ArrayIndexOutOfBoundsException(i); } } }
java
public void set(Vector3d v1) { x = v1.x; y = v1.y; z = v1.z; }
java
public void add(Vector3d v1, Vector3d v2) { x = v1.x + v2.x; y = v1.y + v2.y; z = v1.z + v2.z; }
java
public void add(Vector3d v1) { x += v1.x; y += v1.y; z += v1.z; }
java
public void sub(Vector3d v1, Vector3d v2) { x = v1.x - v2.x; y = v1.y - v2.y; z = v1.z - v2.z; }
java
public void sub(Vector3d v1) { x -= v1.x; y -= v1.y; z -= v1.z; }
java
public double distance(Vector3d v) { double dx = x - v.x; double dy = y - v.y; double dz = z - v.z; return Math.sqrt(dx * dx + dy * dy + dz * dz); }
java
public double distanceSquared(Vector3d v) { double dx = x - v.x; double dy = y - v.y; double dz = z - v.z; return dx * dx + dy * dy + dz * dz; }
java
public double dot(Vector3d v1) { return x * v1.x + y * v1.y + z * v1.z; }
java
public void normalize() { double lenSqr = x * x + y * y + z * z; double err = lenSqr - 1; if (err > (2 * DOUBLE_PREC) || err < -(2 * DOUBLE_PREC)) { double len = Math.sqrt(lenSqr); x /= len; y /= len; z /= len; } }
java
public void cross(Vector3d v1, Vector3d v2) { double tmpx = v1.y * v2.z - v1.z * v2.y; double tmpy = v1.z * v2.x - v1.x * v2.z; double tmpz = v1.x * v2.y - v1.y * v2.x; x = tmpx; y = tmpy; z = tmpz; }
java
protected void setRandom(double lower, double upper, Random generator) { double range = upper - lower; x = generator.nextDouble() * range + lower; y = generator.nextDouble() * range + lower; z = generator.nextDouble() * range + lower; }
java
public LuaScriptBlock endBlockReturn(LuaValue value) { add(new LuaAstReturnStatement(argument(value))); return new LuaScriptBlock(script); }
java
public static LuaCondition isNull(LuaValue value) { LuaAstExpression expression; if (value instanceof LuaLocal) { expression = new LuaAstLocal(((LuaLocal) value).getName()); } else { throw new IllegalArgumentException("Unexpected value type: " + value.getClass().getName()); } return new LuaCondition(new LuaAstNot(expression)); }
java
public String getVertexString() { if (tail() != null) { return "" + tail().index + "-" + head().index; } else { return "?-" + head().index; } }
java
public static Face createTriangle(Vertex v0, Vertex v1, Vertex v2, double minArea) { Face face = new Face(); HalfEdge he0 = new HalfEdge(v0, face); HalfEdge he1 = new HalfEdge(v1, face); HalfEdge he2 = new HalfEdge(v2, face); he0.prev = he2; he0.next = he1; he1.prev = he0; he1.next = he2; he2.prev = he1; he2.next = he0; face.he0 = he0; // compute the normal and offset face.computeNormalAndCentroid(minArea); return face; }
java
public double distanceToPlane(Point3d p) { return normal.x * p.x + normal.y * p.y + normal.z * p.z - planeOffset; }
java
public HalfEdge getEdge(int i) { HalfEdge he = he0; while (i > 0) { he = he.next; i--; } while (i < 0) { he = he.prev; i++; } return he; }
java
public double areaSquared(HalfEdge hedge0, HalfEdge hedge1) { Point3d p0 = hedge0.tail().pnt; Point3d p1 = hedge0.head().pnt; Point3d p2 = hedge1.head().pnt; double dx1 = p1.x - p0.x; double dy1 = p1.y - p0.y; double dz1 = p1.z - p0.z; double dx2 = p2.x - p0.x; double dy2 = p2.y - p0.y; double dz2 = p2.z - p0.z; double x = dy1 * dz2 - dz1 * dy2; double y = dz1 * dx2 - dx1 * dz2; double z = dx1 * dy2 - dy1 * dx2; return x * x + y * y + z * z; }
java
protected <T> T fromJsonString(String json, Class<T> clazz) { return _gsonParser.fromJson(json, clazz); }
java
public LuaScript endScript(LuaScriptConfig config) { if (!endsWithReturnStatement()) { add(new LuaAstReturnStatement()); } String scriptText = buildScriptText(); return new BasicLuaScript(scriptText, config); }
java
public LuaScript endScriptReturn(LuaValue value, LuaScriptConfig config) { add(new LuaAstReturnStatement(argument(value))); String scriptText = buildScriptText(); return new BasicLuaScript(scriptText, config); }
java
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
public LuaPreparedScript endPreparedScriptReturn(LuaValue value, LuaScriptConfig config) { add(new LuaAstReturnStatement(argument(value))); return endPreparedScript(config); }
java
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
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
public long remove(final String... fields) { return doWithJedis(new JedisCallable<Long>() { @Override public Long call(Jedis jedis) { return jedis.hdel(getKey(), fields); } }); }
java
public Double score(final String member) { return doWithJedis(new JedisCallable<Double>() { @Override public Double call(Jedis jedis) { return jedis.zscore(getKey(), member); } }); }
java
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
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
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
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
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
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
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
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
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
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
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
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
public Point3d[] getVertices() { Point3d[] vtxs = new Point3d[numVertices]; for (int i = 0; i < numVertices; i++) { vtxs[i] = pointBuffer[vertexPointIndices[i]].pnt; } return vtxs; }
java
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
public int[] getVertexPointIndices() { int[] indices = new int[numVertices]; for (int i = 0; i < numVertices; i++) { indices[i] = vertexPointIndices[i]; } return indices; }
java
public long addAll(final String... members) { return doWithJedis(new JedisCallable<Long>() { @Override public Long call(Jedis jedis) { return jedis.sadd(getKey(), members); } }); }
java
public long removeAll(final String... members) { return doWithJedis(new JedisCallable<Long>() { @Override public Long call(Jedis jedis) { return jedis.srem(getKey(), members); } }); }
java
public String pop() { return doWithJedis(new JedisCallable<String>() { @Override public String call(Jedis jedis) { return jedis.spop(getKey()); } }); }
java
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
public long indexOf(final String element) { return doWithJedis(new JedisCallable<Long>() { @Override public Long call(Jedis jedis) { return doIndexOf(jedis, element); } }); }
java
public String get(final long index) { return doWithJedis(new JedisCallable<String>() { @Override public String call(Jedis jedis) { return jedis.lindex(getKey(), index); } }); }
java
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
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
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
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
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
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
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
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
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
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
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
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
public static Class getClass(String className, boolean initialize) throws ClassNotFoundException { return Class.forName(className, initialize, getClassLoader()); }
java
public static Object newInstance(Class target, Class[] types, Object[] args) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { return newInstance(target, types, args, false); }
java
public static Field getField(Class clazz, String fieldName) { try { return clazz.getField(fieldName); } catch (Exception ignored) {} return null; }
java
public static Object newInstance(String className) throws InstantiationException, IllegalAccessException, ClassNotFoundException { return newInstance(getClass(className)); }
java
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
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
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
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
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
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
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
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
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
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
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