public List<Variable> fields() { int fieldOffset = SpscOffHeapFixedSizeRingBuffer.MESSAGE_INDICATOR_SIZE; List<Variable> fields = new ArrayList<Variable>(); for (Method method : inspector.getters) { Primitive type = Primitive.of(method.getReturnType()); String name = method.getName().substring(3); fields.add( new Variable( type.javaEquivalent.getName(), name, fieldOffset, type.unsafeMethodSuffix())); fieldOffset += type.sizeInBytes; } return fields; }
private <T extends PropertyContainer> void deleteFromTrackers( Primitive primitive, List<PropertyTracker<T>> trackers) { if (!trackers.isEmpty()) { Iterable<String> propertyKeys = primitive.getPropertyKeys(this); T proxy = (T) primitive.asProxy(this); for (String key : propertyKeys) { Object value = primitive.getProperty(this, key); for (PropertyTracker<T> tracker : trackers) { tracker.propertyRemoved(proxy, key, value); } } } }
@Override void updateFromNative() { super.updateFromNative(); int vtxCount = mRS.nMeshGetVertexBufferCount(getID(mRS)); int idxCount = mRS.nMeshGetIndexCount(getID(mRS)); long[] vtxIDs = new long[vtxCount]; long[] idxIDs = new long[idxCount]; int[] primitives = new int[idxCount]; mRS.nMeshGetVertices(getID(mRS), vtxIDs, vtxCount); mRS.nMeshGetIndices(getID(mRS), idxIDs, primitives, idxCount); mVertexBuffers = new Allocation[vtxCount]; mIndexBuffers = new Allocation[idxCount]; mPrimitives = new Primitive[idxCount]; for (int i = 0; i < vtxCount; i++) { if (vtxIDs[i] != 0) { mVertexBuffers[i] = new Allocation(vtxIDs[i], mRS, null, Allocation.USAGE_SCRIPT); mVertexBuffers[i].updateFromNative(); } } for (int i = 0; i < idxCount; i++) { if (idxIDs[i] != 0) { mIndexBuffers[i] = new Allocation(idxIDs[i], mRS, null, Allocation.USAGE_SCRIPT); mIndexBuffers[i].updateFromNative(); } mPrimitives[i] = Primitive.values()[primitives[i]]; } }
public static PrimitiveIntSet asSetAllowDuplicates(PrimitiveIntIterator iterator) { PrimitiveIntSet set = Primitive.intSet(); while (iterator.hasNext()) { set.add(iterator.next()); } return set; }
public static PrimitiveIntSet asSet(int[] values) { PrimitiveIntSet set = Primitive.intSet(values.length); for (int value : values) { set.add(value); } return set; }
@Override public ArrayMap<Integer, DefinedProperty> getCowPropertyAddMap(Primitive primitive) { if (primitiveElement == null) { return null; } CowEntityElement element = primitive.getEntityElement(primitiveElement, false); return element != null ? element.getPropertyAddMap(false) : null; }
public Object invokeImpl(Object proxy, Method method, Object[] args) throws EvalError { String methodName = method.getName(); CallStack callstack = new CallStack(namespace); /* If equals() is not explicitly defined we must override the default implemented by the This object protocol for scripted object. To support XThis equals() must test for equality with the generated proxy object, not the scripted bsh This object; otherwise callers from outside in Java will not see a the proxy object as equal to itself. */ BshMethod equalsMethod = null; try { equalsMethod = namespace.getMethod("equals", new Class[] {Object.class}); } catch (UtilEvalError e) { /*leave null*/ } if (methodName.equals("equals") && equalsMethod == null) { Object obj = args[0]; return new Boolean(proxy == obj); } /* If toString() is not explicitly defined override the default to show the proxy interfaces. */ BshMethod toStringMethod = null; try { toStringMethod = namespace.getMethod("toString", new Class[] {}); } catch (UtilEvalError e) { /*leave null*/ } if (methodName.equals("toString") && toStringMethod == null) { Class[] ints = proxy.getClass().getInterfaces(); // XThis.this refers to the enclosing class instance StringBuilder sb = new StringBuilder(XThis.this.toString() + "\nimplements:"); for (int i = 0; i < ints.length; i++) sb.append(" " + ints[i].getName() + ((ints.length > 1) ? "," : "")); return sb.toString(); } Class[] paramTypes = method.getParameterTypes(); return Primitive.unwrap(invokeMethod(methodName, Primitive.wrap(args, paramTypes))); }
public static PrimitiveIntSet asSet(PrimitiveIntIterator iterator) { PrimitiveIntSet set = Primitive.intSet(); while (iterator.hasNext()) { int next = iterator.next(); if (!set.add(next)) { throw new IllegalStateException("Duplicate " + next + " from " + iterator); } } return set; }
@Test public void testTerserGetPrimitive_VariesCompositeFirstComponent() throws HL7Exception { final Varies variesField = new Varies(mshOnly); final Primitive comp1Sub1 = Terser.getPrimitive(variesField, 1, 1); comp1Sub1.setValue("comp1Sub1"); final Primitive comp1Sub2 = Terser.getPrimitive(variesField, 1, 2); comp1Sub2.setValue("comp1Sub2"); final Primitive comp2Sub1 = Terser.getPrimitive(variesField, 2, 1); comp2Sub1.setValue("comp2Sub1"); assertEquals(GenericComposite.class, variesField.getData().getClass()); final GenericComposite field = (GenericComposite) variesField.getData(); final Type typeComp1 = field.getComponent(0); assertEquals(typeComp1.getClass(), Varies.class); final Varies variesComp1 = (Varies) typeComp1; assertEquals(GenericComposite.class, variesComp1.getData().getClass()); final GenericComposite comp1 = (GenericComposite) variesComp1.getData(); final Type typeSub1 = comp1.getComponent(1); assertEquals(typeSub1.getClass(), Varies.class); final Varies variesSub1 = (Varies) typeSub1; assertEquals(GenericPrimitive.class, variesSub1.getData().getClass()); assertEquals("comp1Sub1&comp1Sub2^comp2Sub1", PipeParser.encode(variesField, encoders)); }
@Override public void execute() { // 包格式:序列化的原语|源标签 if (this.packet.getSubsegmentCount() < 2) { Logger.e(ServerDialogueCommand.class, "Dialogue packet format error"); return; } byte[] priData = this.packet.getSubsegment(0); ByteArrayInputStream stream = new ByteArrayInputStream(priData); byte[] tagData = this.packet.getSubsegment(1); String speakerTag = Utils.bytes2String(tagData); byte[] identifierData = this.packet.getSubsegment(2); // 反序列化原语 Primitive primitive = new Primitive(speakerTag); primitive.read(stream); this.service.processDialogue( this.session, speakerTag, Utils.bytes2String(identifierData), primitive); }
@Test public void shouldInvokePrimitives() { Primitive primitive = new Primitive("primitive:", 2, "43"); primitive.accept(analyser); verify(writer).invokePrimitive(2, "43"); }
/** * Copies all node information from <code>originalNode</code> into the current node. This method * is called from the <code>cloneNode</code> method which is, in turn, called by the <code> * cloneTree</code> method. * * <p>For any <i>NodeComponent</i> objects contained by the object being duplicated, each * <i>NodeComponent</i> object's <code>duplicateOnCloneTree</code> value is used to determine * whether the <i>NodeComponent</i> should be duplicated in the new node or if just a reference to * the current node should be placed in the new node. This flag can be overridden by setting the * <code>forceDuplicate</code> parameter in the <code>cloneTree</code> method to <code>true</code> * . * * @param originalNode the original node to duplicate. * @param forceDuplicate when set to <code>true</code>, causes the <code>duplicateOnCloneTree * </code> flag to be ignored. When <code>false</code>, the value of each node's <code> * duplicateOnCloneTree</code> variable determines whether NodeComponent data is duplicated or * copied. * @see Node#cloneTree * @see Node#cloneNode * @see NodeComponent#setDuplicateOnCloneTree */ @Override public void duplicateNode(Node originalNode, boolean forceDuplicate) { super.duplicateNode(originalNode, forceDuplicate); }
public Object eval(CallStack callstack, Interpreter interpreter) throws EvalError { Object lhs = ((SimpleNode) jjtGetChild(0)).eval(callstack, interpreter); /* Doing instanceof? Next node is a type. */ if (kind == INSTANCEOF) { // null object ref is not instance of any type if (lhs == Primitive.NULL) return new Primitive(false); Class rhs = ((BSHType) jjtGetChild(1)).getType(callstack, interpreter); /* // primitive (number or void) cannot be tested for instanceof if (lhs instanceof Primitive) throw new EvalError("Cannot be instance of primitive type." ); */ /* Primitive (number or void) is not normally an instanceof anything. But for internal use we'll test true for the bsh.Primitive class. i.e. (5 instanceof bsh.Primitive) will be true */ if (lhs instanceof Primitive) if (rhs == lib.bsh.Primitive.class) return new Primitive(true); else return new Primitive(false); // General case - performe the instanceof based on assignability boolean ret = Types.isJavaBaseAssignable(rhs, lhs.getClass()); return new Primitive(ret); } // The following two boolean checks were tacked on. // This could probably be smoothed out. /* Look ahead and short circuit evaluation of the rhs if: we're a boolean AND and the lhs is false. */ if (kind == BOOL_AND || kind == BOOL_ANDX) { Object obj = lhs; if (isPrimitiveValue(lhs)) obj = ((Primitive) lhs).getValue(); if (obj instanceof Boolean && (((Boolean) obj).booleanValue() == false)) return new Primitive(false); } /* Look ahead and short circuit evaluation of the rhs if: we're a boolean AND and the lhs is false. */ if (kind == BOOL_OR || kind == BOOL_ORX) { Object obj = lhs; if (isPrimitiveValue(lhs)) obj = ((Primitive) lhs).getValue(); if (obj instanceof Boolean && (((Boolean) obj).booleanValue() == true)) return new Primitive(true); } // end stuff that was tacked on for boolean short-circuiting. /* Are both the lhs and rhs either wrappers or primitive values? do binary op */ boolean isLhsWrapper = isWrapper(lhs); Object rhs = ((SimpleNode) jjtGetChild(1)).eval(callstack, interpreter); boolean isRhsWrapper = isWrapper(rhs); if ((isLhsWrapper || isPrimitiveValue(lhs)) && (isRhsWrapper || isPrimitiveValue(rhs))) { // Special case for EQ on two wrapper objects if ((isLhsWrapper && isRhsWrapper && kind == EQ)) { /* Don't auto-unwrap wrappers (preserve identity semantics) FALL THROUGH TO OBJECT OPERATIONS BELOW. */ } else try { return Primitive.binaryOperation(lhs, rhs, kind); } catch (UtilEvalError e) { throw e.toEvalError(this, callstack); } } /* Doing the following makes it hard to use untyped vars... e.g. if ( arg == null ) ...what if arg is a primitive? The answer is that we should test only if the var is typed...? need to get that info here... else { // Do we have a mixture of primitive values and non-primitives ? // (primitiveValue = not null, not void) int primCount = 0; if ( isPrimitiveValue( lhs ) ) ++primCount; if ( isPrimitiveValue( rhs ) ) ++primCount; if ( primCount > 1 ) // both primitive types, should have been handled above throw new InterpreterError("should not be here"); else if ( primCount == 1 ) // mixture of one and the other throw new EvalError("Operator: '" + tokenImage[kind] +"' inappropriate for object / primitive combination.", this, callstack ); // else fall through to handle both non-primitive types // end check for primitive and non-primitive mix } */ /* Treat lhs and rhs as arbitrary objects and do the operation. (including NULL and VOID represented by their Primitive types) */ // System.out.println("binary op arbitrary obj: {"+lhs+"}, {"+rhs+"}"); switch (kind) { case EQ: return new Primitive((lhs == rhs)); case NE: return new Primitive((lhs != rhs)); case PLUS: if (lhs instanceof String || rhs instanceof String) return lhs.toString() + rhs.toString(); // FALL THROUGH TO DEFAULT CASE!!! default: if (lhs instanceof Primitive || rhs instanceof Primitive) if (lhs == Primitive.VOID || rhs == Primitive.VOID) throw new EvalError( "illegal use of undefined variable, class, or 'void' literal", this, callstack); else if (lhs == Primitive.NULL || rhs == Primitive.NULL) throw new EvalError("illegal use of null value or 'null' literal", this, callstack); throw new EvalError( "Operator: '" + tokenImage[kind] + "' inappropriate for objects", this, callstack); } }
@Override void accept(ExpressionWriter writer, int lprec, int rprec) { // "new Function1() { // public Result apply(T1 p1, ...) { // <body> // } // // bridge method // public Object apply(Object p1, ...) { // return apply((T1) p1, ...); // } // } // // if any arguments are primitive there is an extra bridge method: // // new Function1() { // public double apply(double p1, int p2) { // <body> // } // // box bridge method // public Double apply(Double p1, Integer p2) { // return apply(p1.doubleValue(), p2.intValue()); // } // // bridge method // public Object apply(Object p1, Object p2) { // return apply((Double) p1, (Integer) p2); // } List<String> params = new ArrayList<String>(); List<String> bridgeParams = new ArrayList<String>(); List<String> bridgeArgs = new ArrayList<String>(); List<String> boxBridgeParams = new ArrayList<String>(); List<String> boxBridgeArgs = new ArrayList<String>(); for (ParameterExpression parameterExpression : parameterList) { final Type parameterType = parameterExpression.getType(); final Type parameterBoxType = Types.box(parameterType); final String parameterBoxTypeName = Types.className(parameterBoxType); params.add(parameterExpression.declString()); bridgeParams.add(parameterExpression.declString(Object.class)); bridgeArgs.add("(" + parameterBoxTypeName + ") " + parameterExpression.name); boxBridgeParams.add(parameterExpression.declString(parameterBoxType)); boxBridgeArgs.add( parameterExpression.name + (Primitive.is(parameterType) ? "." + Primitive.of(parameterType).primitiveName + "Value()" : "")); } Type bridgeResultType = Functions.FUNCTION_RESULT_TYPES.get(this.type); if (bridgeResultType == null) { bridgeResultType = body.getType(); } Type resultType2 = bridgeResultType; if (bridgeResultType == Object.class && !params.equals(bridgeParams) && !(body.getType() instanceof TypeVariable)) { resultType2 = body.getType(); } String methodName = getAbstractMethodName(); writer .append("new ") .append(type) .append("()") .begin(" {\n") .append("public ") .append(Types.className(resultType2)) .list(" " + methodName + "(", ", ", ") ", params) .append(Blocks.toFunctionBlock(body)); // Generate an intermediate bridge method if at least one parameter is // primitive. if (!boxBridgeParams.equals(params)) { writer .append("public ") .append(Types.boxClassName(bridgeResultType)) .list(" " + methodName + "(", ", ", ") ", boxBridgeParams) .begin("{\n") .list("return " + methodName + "(\n", ",\n", ");\n", boxBridgeArgs) .end("}\n"); } // Generate a bridge method. Argument types are looser (as if every // type parameter is set to 'Object'). // // Skip the bridge method if there are no arguments. It would have the // same overload as the regular method. if (!bridgeParams.equals(params)) { writer .append("public ") .append(Types.boxClassName(bridgeResultType)) .list(" " + methodName + "(", ", ", ") ", bridgeParams) .begin("{\n") .list("return " + methodName + "(\n", ",\n", ");\n", bridgeArgs) .end("}\n"); } writer.end("}\n"); }
Primitive getReturn(Method method) { return Primitive.of(method.getReturnType()); }
private boolean executeAll(File velocitySources, File outputDirectory) throws MojoExecutionException { List<File> files = new ArrayList<File>(); String canoPath; try { velocitySources = velocitySources.getCanonicalFile(); listVeloFiles(velocitySources, files); canoPath = sourcePathRoot.getCanonicalPath(); System.out.println("Velocity root path = " + canoPath); Velocity.setProperty("file.resource.loader.path", canoPath); // file.getParent()); Velocity.init(); } catch (Exception ex) { throw new MojoExecutionException("Failed to list files from '" + velocitySources + "'", ex); } getLog().info("Found " + files.size() + " files in '" + velocitySources + "'..."); if (files.isEmpty()) return false; for (File file : files) { try { file = file.getCanonicalFile(); String name = file.getName(); if (name.endsWith("~") || name.endsWith(".bak")) { getLog().info("Skipping: '" + name + "'"); continue; } File outFile = getOutputFile(file, velocitySources, outputDirectory); if (outFile.exists() && outFile.lastModified() > file.lastModified()) { getLog().info("Up-to-date: '" + name + "'"); continue; } getLog().info("Executing template '" + name + "'..."); // context = new VelocityContext(); String cano = file.getCanonicalPath(); cano = cano.substring(canoPath.length()); if (cano.startsWith(File.separator)) cano = cano.substring(File.separator.length()); org.apache.velocity.Template template = Velocity.getTemplate(cano); // file.getName()); VelocityContext context = new VelocityContext(); // execution.getParameters()); context.put("primitives", Primitive.getPrimitives()); context.put("primitivesNoBool", Primitive.getPrimitivesNoBool()); context.put("bridJPrimitives", Primitive.getBridJPrimitives()); StringWriter out = new StringWriter(); template.merge(context, out); out.close(); outFile.getParentFile().mkdirs(); FileWriter f = new FileWriter(outFile); f.write(out.toString()); f.close(); // getLog().info("\tGenerated '" + outFile.getName() + "'"); } catch (Exception ex) { // throw new MojoExecutionException("Failed to execute template '" + file + "'", ex) .printStackTrace(); } } return true; }
/** * Construct the array from the initializer syntax. * * @param baseType the base class type of the array (no dimensionality) * @param dimensions the top number of dimensions of the array e.g. 2 for a String [][]; */ public Object eval(Class baseType, int dimensions, CallStack callstack, Interpreter interpreter) throws EvalError { int numInitializers = jjtGetNumChildren(); // allocate the array to store the initializers int[] dima = new int[dimensions]; // description of the array // The other dimensions default to zero and are assigned when // the values are set. dima[0] = numInitializers; Object initializers = Array.newInstance(baseType, dima); // Evaluate the initializers for (int i = 0; i < numInitializers; i++) { SimpleNode node = (SimpleNode) jjtGetChild(i); Object currentInitializer; if (node instanceof BSHArrayInitializer) { if (dimensions < 2) throw new EvalError("Invalid Location for Intializer, position: " + i, this, callstack); currentInitializer = ((BSHArrayInitializer) node).eval(baseType, dimensions - 1, callstack, interpreter); } else currentInitializer = node.eval(callstack, interpreter); if (currentInitializer == Primitive.VOID) throw new EvalError("Void in array initializer, position" + i, this, callstack); // Determine if any conversion is necessary on the initializers. // // Quick test to see if conversions apply: // If the dimensionality of the array is 1 then the elements of // the initializer can be primitives or boxable types. If it is // greater then the values must be array (object) types and there // are currently no conversions that we do on those. // If we have conversions on those in the future then we need to // get the real base type here instead of the dimensionless one. Object value = currentInitializer; if (dimensions == 1) { // We do a bsh cast here. strictJava should be able to affect // the cast there when we tighten control try { value = Types.castObject(currentInitializer, baseType, Types.CAST); } catch (UtilEvalError e) { throw e.toEvalError("Error in array initializer", this, callstack); } // unwrap any primitive, map voids to null, etc. value = Primitive.unwrap(value); } // store the value in the array try { Array.set(initializers, i, value); } catch (IllegalArgumentException e) { Interpreter.debug("illegal arg" + e); throwTypeError(baseType, currentInitializer, i, callstack); } catch (ArrayStoreException e) { // I think this can happen Interpreter.debug("arraystore" + e); throwTypeError(baseType, currentInitializer, i, callstack); } } return initializers; }
@Override public ArrayMap<Integer, DefinedProperty> getOrCreateCowPropertyRemoveMap(Primitive primitive) { return primitive.getEntityElement(getPrimitiveElement(true), true).getPropertyRemoveMap(true); }