generate js service in packagePath.fn in classes directory/packagePath

@param element
@param visitor
@param packagePath
@param fn
194683
void writeJsFile(TypeElement element, ElementVisitor visitor, String packagePath, String fn) {
		try (Writer w = fws.getFileObjectWriterInClassOutput(packagePath, fn)) {
			element.accept(visitor, w);
		} catch (IOException ioe) {
			messager.printMessage(Diagnostic.Kind.MANDATORY_WARNING, " FAILED TO CREATE : " + packagePath + "." + fn);
		}
	}
252994
@Override
  protected void visitSoyFileNode(SoyFileNode node) {
    StringBuilder file = new StringBuilder();

    file.append("// This file was automatically generated from ")
        .append(node.getFileName())
        .append(".\n");
    file.append("// Please don't edit this file by hand.\n");

    // Output a section containing optionally-parsed compiler directives in comments. Since these
    // are comments, they are not controlled by an option, and will be removed by minifiers that do
    // not understand them.
    file.append("\n");
    String fileOverviewDescription = "Templates in namespace " + node.getNamespace() + ".";
    JsDoc.Builder jsDocBuilder = JsDoc.builder();
    jsDocBuilder.addAnnotation("fileoverview", fileOverviewDescription);
    if (node.getDelPackageName() != null) {
      jsDocBuilder.addParameterizedAnnotation("modName", node.getDelPackageName());
    }
    addJsDocToProvideDelTemplates(jsDocBuilder, node);
    addJsDocToRequireDelTemplates(jsDocBuilder, node);
    addCodeToRequireCss(jsDocBuilder, node);
    jsDocBuilder.addAnnotation("public");
    file.append(jsDocBuilder.build());
    file.append("\n\n");

    // Add code to define JS namespaces or add provide/require calls for Closure Library.
    templateAliases = AliasUtils.IDENTITY_ALIASES;
    jsCodeBuilder = createCodeBuilder();

    if (jsSrcOptions.shouldGenerateGoogModules()) {
      templateAliases = AliasUtils.createTemplateAliases(node);

      addCodeToDeclareGoogModule(file, node);
      addCodeToRequireGoogModules(node);
    } else if (jsSrcOptions.shouldProvideRequireSoyNamespaces()) {
      addCodeToProvideSoyNamespace(file, node);
      file.append('\n');
      addCodeToRequireSoyNamespaces(node);
    } else {
      throw new AssertionError("impossible");
    }

    // add declarations for the ijdata params
    // This takes advantage of the way '@record' types in closure are 'open'.
    // Unfortunately clutz doesn't understand this:
    // https://github.com/angular/clutz/issues/832
    // So TS users will not be able to see the property definitions.
    // The most practical solution to that is for soy to generate its own .d.ts files.
    Map<String, SoyType> ijData = getAllIjDataParams(node);
    if (!ijData.isEmpty()) {
      GoogRequire require = GoogRequire.create("soy");
      jsCodeBuilder.appendLine();
      for (Map.Entry<String, SoyType> entry : ijData.entrySet()) {
        jsCodeBuilder.appendLine();
        //
        jsCodeBuilder.appendLine(
            JsDoc.builder()
                // Because every declaration can declare a type, we can get errors if they don't
                // declare identical types.  There isn't a good way to force identical declarations
                // so we just suppress the duplicate error warning.
                .addParameterizedAnnotation("suppress", "duplicate")
                // declare every field as optional.  This is because if a template is unused and
                // declares an ij param we don't want to force people to supply a value.
                .addParameterizedAnnotation(
                    "type",
                    getJsTypeForParamForDeclaration(entry.getValue()).typeExpr() + "|undefined")
                .build()
                .toString());
        jsCodeBuilder.append(
            require
                .reference()
                .dotAccess("IjData")
                .dotAccess("prototype")
                .dotAccess(entry.getKey())
                .asStatement());
      }
    }

    // Add code for each template.
    for (TemplateNode template : node.getChildren()) {
      jsCodeBuilder.appendLine().appendLine();
      staticVarDeclarations = new ArrayList<>();
      visit(template);
      if (!staticVarDeclarations.isEmpty()) {
        jsCodeBuilder.append(Statement.of(staticVarDeclarations));
      }
    }
    jsCodeBuilder.appendGoogRequiresTo(file);
    jsCodeBuilder.appendCodeTo(file);
    jsFilesContents.add(file.toString());
    jsCodeBuilder = null;
  }
1353842
public ClassNode visitPublicNotAbstractTreeNodes($.Visitor<ClassNode> visitor) {
        return visitTree($.guardedVisitor(new $.Predicate<ClassNode>() {
            @Override
            public boolean test(ClassNode classNode) {
                return classNode.publicNotAbstract();
            }
        }, visitor));
    }
235241
@Override
	@SuppressWarnings({"checkstyle:methodlength", "checkstyle:cyclomaticcomplexity",
			"checkstyle:npathcomplexity", "checkstyle:booleanexpressioncomplexity"})
	protected void transform(final XtendFunction source, final JvmGenericType container, boolean allowDispatch) {
		final GenerationContext context = getContext(container);

		// Compute the operation name
		// Issue #355: null or empty name is possible.
		final String originalFunctionName = source.getName();
		if (!Strings.isNullOrEmpty(originalFunctionName)) {
			final StringBuilder sourceNameBuffer = new StringBuilder(originalFunctionName);
			if (allowDispatch && source.isDispatch()) {
				sourceNameBuffer.insert(0, "_"); //$NON-NLS-1$
			}
			final String sourceName = sourceNameBuffer.toString();

			// Create the main function
			final JvmOperation operation = this.typesFactory.createJvmOperation();
			container.getMembers().add(operation);
			operation.setSimpleName(sourceName);
			setVisibility(operation, source);
			operation.setStrictFloatingPoint(source.isStrictFloatingPoint());
			operation.setStatic(source.isStatic());
			operation.setSynchronized(source.isSynchonized());
			operation.setNative(source.isNative());
			boolean enableFunctionBody;
			if (container.isInterface()) {
				enableFunctionBody = false;
				if (context != null && context.isAtLeastJava8()
						&& !Utils.toLightweightTypeReference(container, this.services).isSubtypeOf(Capacity.class)) {
					if (operation.isStatic()) {
						enableFunctionBody = true;
					} else if (source.getExpression() != null && !operation.isAbstract()) {
						enableFunctionBody = true;
					}
				}
				operation.setDefault(enableFunctionBody && !operation.isStatic());
				operation.setAbstract(!enableFunctionBody);
				operation.setFinal(false);
			} else {
				operation.setDefault(false);
				enableFunctionBody = context != null && !source.isAbstract();
				operation.setAbstract(!enableFunctionBody);
				operation.setFinal(enableFunctionBody && source.isFinal());
			}
			this.associator.associatePrimary(source, operation);

			// Type parameters
			copyAndFixTypeParameters(source.getTypeParameters(), operation);

			// Compute the identifier of the action.
			final QualifiedActionName actionKey = this.sarlSignatureProvider.createQualifiedActionName(
					container, sourceName);

			// Compute the different action prototypes associated to the action to create.
			final boolean isVarArgs = Utils.isVarArg(source.getParameters());
			final InferredPrototype actionSignatures = this.sarlSignatureProvider.createPrototypeFromSarlModel(
					actionKey,
					isVarArgs, source.getParameters());

			// Compute the action prototype of the action without optional parameter
			final ActionPrototype actSigKey = this.sarlSignatureProvider.createActionPrototype(
					sourceName,
					actionSignatures.getFormalParameterTypes());

			// Generate the parameters
			final List<InferredStandardParameter> paramList = actionSignatures.getOriginalParameterTypes();
			translateSarlFormalParameters(
					context,
					operation, container, isVarArgs,
					source.getParameters(),
					container.isInterface(), paramList);

			// Get the super function
			final JvmOperation inheritedOperation;
			if (context != null) {
				JvmOperation tmpInheritedOperation = context.getInheritedFinalOperations().get(actSigKey);
				if (tmpInheritedOperation == null) {
					tmpInheritedOperation = context.getInheritedOverridableOperations().get(actSigKey);
				}
				if (tmpInheritedOperation == null) {
					tmpInheritedOperation = context.getInheritedOperationsToImplement().get(actSigKey);
				}
				inheritedOperation = tmpInheritedOperation;
			} else {
				inheritedOperation = null;
			}

			// Infer the return type
			final JvmTypeReference selectedReturnType = inferFunctionReturnType(source, operation, inheritedOperation);
			operation.setReturnType(selectedReturnType);

			// Exceptions
			for (final JvmTypeReference exception : source.getExceptions()) {
				operation.getExceptions().add(this.typeBuilder.cloneWithProxies(exception));
			}

			// Add the body
			if (enableFunctionBody) {
				setBody(operation, source.getExpression());
			}

			// User Annotations
			translateAnnotationsTo(source.getAnnotations(), operation);

			// Add @Inline annotation
			if (context != null && context.isAtLeastJava8()
					&& context.getGeneratorConfig2().isGenerateInlineAnnotation()
					&& !source.isAbstract() && !container.isInterface()
					&& (source.isStatic() || source.isFinal() || container.isFinal())
					&& context.getParentContext() == null
					&& this.annotationFinder.findAnnotation(operation, Inline.class) == null) {
				context.getPostFinalizationElements().add(
						() -> this.inlineExpressionCompiler.appendInlineAnnotation(operation, source));
			}

			// Add @Override annotation
			if (source.isOverride()
					&& this.annotationFinder.findAnnotation(operation, Override.class) == null
					&& this.typeReferences.findDeclaredType(Override.class, source) != null) {
				addAnnotationSafe(operation, Override.class);
			}

			// Add @Pure annotation
			final boolean addDynamicPureAnnotationGenerator;
			final boolean hasExplicitPureAnnotation = this.annotationFinder.findAnnotation(operation, Pure.class) != null;
			if (context != null && context.getGeneratorConfig2().isGeneratePureAnnotation()
					&& !hasExplicitPureAnnotation && this.typeReferences.findDeclaredType(Pure.class, source) != null) {
				addDynamicPureAnnotationGenerator = inheritedOperation == null;
				if (addDynamicPureAnnotationGenerator) {
					this.operationHelper.attachPureAnnotationAdapter(operation, (op, helper) -> {
						return helper.isPurableOperation(source);
					});
				} else {
					this.operationHelper.attachPureAnnotationAdapter(operation, (op, helper) -> {
						return helper.isPureOperation(inheritedOperation);
					});
				}
			} else {
				addDynamicPureAnnotationGenerator = false;
			}

			// Detecting if the action is an early-exit action.
			// If true, the Java code is annotated to be usable by the SARL validator.
			final List<JvmTypeReference> firedEvents;
			final boolean isEarlyExit;
			if (source instanceof SarlAction) {
				final SarlAction action = (SarlAction) source;
				firedEvents = action.getFiredEvents();
				isEarlyExit = this.earlyExitComputer.isEarlyExitOperation(action);
				if (isEarlyExit) {
					addAnnotationSafe(operation, EarlyExit.class);
				}
			} else {
				firedEvents = Collections.emptyList();
				isEarlyExit = false;
			}

			// Put the fired SARL events as Java annotations for being usable by the SARL validator.
			if (!firedEvents.isEmpty()) {
				operation.getAnnotations().add(annotationClassRef(FiredEvent.class, firedEvents));
			}

			// 1. Ensure that the Java annotations related to the default value are really present.
			//    They may be not present if the generated action is a specific version of an inherited
			//    action with default values for parameters.
			// 2. Update the two collections that describes the implemented and implementable operations.
			if (context != null) {
				final JvmOperation implementedOperation = context.getInheritedOperationsToImplement().remove(actSigKey);
				// Put the annotations that were defined in the implemented operation
				if (implementedOperation != null) {
					if (this.annotationFinder.findAnnotation(implementedOperation, DefaultValueSource.class) != null
							&& this.annotationFinder.findAnnotation(operation, DefaultValueSource.class) == null) {
						addAnnotationSafe(operation, DefaultValueSource.class);
					}
					// Reinject the @DefaultValue annotations
					final List<JvmFormalParameter> oparams = implementedOperation.getParameters();
					final List<JvmFormalParameter> cparams = operation.getParameters();
					assert oparams.size() == cparams.size();
					for (int i = 0; i < oparams.size(); ++i) {
						final JvmFormalParameter op = oparams.get(i);
						final JvmFormalParameter cp = cparams.get(i);
						final String ovalue = this.annotationUtils.findStringValue(op, DefaultValue.class);
						if (ovalue != null
								&& this.annotationFinder.findAnnotation(cp, DefaultValue.class) == null) {
							addAnnotationSafe(cp,
									DefaultValue.class,
									this.sarlSignatureProvider.qualifyDefaultValueID(
											implementedOperation.getDeclaringType().getIdentifier(),
											ovalue));
						}
					}
				}
				// Add the main operation into the list of overridable operations
				context.getInheritedOverridableOperations().put(actSigKey, operation);
			}

			copyAndCleanDocumentationTo(source, operation);

			@SuppressWarnings("checkstyle:anoninnerlength")
			final Runnable differedGeneration = () -> {
				// Generate the Java functions that correspond to the action with the parameter default values applied.
				for (final Entry<ActionParameterTypes, List<InferredStandardParameter>> otherSignature
						: actionSignatures.getInferredParameterTypes().entrySet()) {
					final ActionPrototype ak = SARLJvmModelInferrer.this.sarlSignatureProvider.createActionPrototype(
							sourceName,
							otherSignature.getKey());
					if (ak != null
							&& (context == null
							|| (!context.getInheritedFinalOperations().containsKey(ak)
									&& !context.getInheritedOverridableOperations().containsKey(ak)))) {

						// Generate the additional constructor that is invoke the main constructor previously generated.
						final JvmOperation operation2 = SARLJvmModelInferrer.this.typesFactory.createJvmOperation();
						container.getMembers().add(operation2);
						operation2.setSimpleName(operation.getSimpleName());
						operation2.setVisibility(operation.getVisibility());
						operation2.setVarArgs(operation.isVarArgs());
						operation2.setAbstract(operation.isAbstract());
						operation2.setDeprecated(operation.isDeprecated());
						operation2.setStatic(operation.isStatic());
						operation2.setFinal(!operation.isStatic() && !container.isInterface());
						operation2.setNative(false);
						operation2.setStrictFloatingPoint(false);
						operation2.setSynchronized(false);
						this.associator.associate(source, operation2);

						copyTypeParametersFromJvmOperation(operation, operation2);

						for (final JvmTypeReference exception : operation.getExceptions()) {
							operation2.getExceptions().add(SARLJvmModelInferrer.this.typeBuilder
									.cloneWithProxies(exception));
						}

						if (selectedReturnType instanceof XComputedTypeReference) {
							operation2.setReturnType(this.typeReferences.createDelegateTypeReference(selectedReturnType));
						} else {
							operation2.setReturnType(cloneWithTypeParametersAndProxies(selectedReturnType, operation2));
						}

						final List<String> args = translateSarlFormalParametersForSyntheticOperation(
								operation2, container, isVarArgs, otherSignature.getValue());

						if (context != null && context.isAtLeastJava8()) {
							operation2.setDefault(container.isInterface());
							operation2.setAbstract(false);
							setBody(operation2, it -> {
								final JvmTypeReference type = operation2.getReturnType();
								if (!SARLJvmModelInferrer.this.typeReferences.is(type, void.class)) {
									it.append("return "); //$NON-NLS-1$
								}
								it.append(sourceName);
								it.append("("); //$NON-NLS-1$
								it.append(IterableExtensions.join(args, ", ")); //$NON-NLS-1$
								it.append(");"); //$NON-NLS-1$
							});
						} else {
							operation2.setDefault(false);
							operation2.setAbstract(true);
						}

						// @Override annotation
						if (source.isOverride()
								&& SARLJvmModelInferrer.this.annotationFinder.findAnnotation(operation,
								Override.class) == null
								&& SARLJvmModelInferrer.this.typeReferences.findDeclaredType(
										Override.class, source) != null) {
							addAnnotationSafe(
									operation, Override.class);
						}

						// @DefaultValueUse annotation
						addAnnotationSafe(
								operation2, DefaultValueUse.class,
								actionSignatures.getFormalParameterTypes().toString());
						appendGeneratedAnnotation(operation2, context);

						// @EarlyExit annotation
						// If the main action is an early-exit action, the additional operation
						// is also an early-exit operation.
						if (isEarlyExit) {
							addAnnotationSafe(
									operation2, EarlyExit.class);
						}

						// @FiredEvent annotation
						// Put the fired SARL events as Java annotations for being usable by the SARL validator.
						if (!firedEvents.isEmpty()) {
							operation2.getAnnotations().add(
									annotationClassRef(FiredEvent.class, firedEvents));
						}

						// @Pure annotation
						if (addDynamicPureAnnotationGenerator) {
							this.operationHelper.attachPureAnnotationAdapter(operation2, (op, helper) -> {
								return helper.isPureOperation(operation);
							});
						} else if (hasExplicitPureAnnotation) {
							addAnnotationSafe(
									operation2, Pure.class);
						}

						// Copy the annotations from the original operations, and that are not overridden above
						for (final JvmAnnotationReference annotation : operation.getAnnotations()) {
							final String id = annotation.getAnnotation().getIdentifier();
							if (!DefaultValueSource.class.getName().equals(id)
									&& !DefaultValueUse.class.getName().equals(id)
									&& !Pure.class.getName().equals(id)
									&& !EarlyExit.class.getName().equals(id)
									&& !FiredEvent.class.getName().equals(id)
									&& !Inline.class.getName().equals(id)
									&& !Generated.class.getName().equals(id)) {
								try {
									final JvmAnnotationReference clone = SARLJvmModelInferrer.this._annotationTypesBuilder
											.annotationRef(id);
									for (final JvmAnnotationValue annotationValue : annotation.getExplicitValues()) {
										clone.getExplicitValues().add(EcoreUtil.copy(annotationValue));
									}
									operation2.getAnnotations().add(clone);
								} catch (IllegalArgumentException exception) {
									// ignore
								}
							}
						}

						// Copy and clean the documentation
						copyAndCleanDocumentationTo(operation, operation2);

						// Update the two collections that describes the implemented and implementable operations.
						if (context != null) {
							context.getInheritedOperationsToImplement().remove(ak);
							context.getInheritedOverridableOperations().put(ak, operation2);
						}
					}
				}
			};

			if (context != null) {
				context.getPreFinalizationElements().add(differedGeneration);
				context.setActionIndex(context.getActionIndex() + 1);
				context.incrementSerial(actSigKey.hashCode());
			} else {
				differedGeneration.run();
			}
		}
	}
1204558
function handlePackage(packagePath) {
  // Read in the package.json.
  var packagePath = path.join(packagePath, 'package.json');
  try {
    var package = require(packagePath);
  } catch (e) {
    console.log('Skipping package ' + packagePath);
    return;
  }

  // Update dependencies as appropriate.
  if (package.dependencies && target in package['dependencies']) {
    package['dependencies'][target] = specifier;
  } else if (package.devDependencies && target in package['devDependencies']) {
    package['devDependencies'][target] = specifier;
  }

  // Write the file back to disk.
  fs.writeFileSync(packagePath, JSON.stringify(package, null, 2) + '\n');
}
300822
@Override
  protected void visitSoyFileNode(SoyFileNode node) {
    templatesInFile = new LinkedHashSet<>();
    for (TemplateNode template : node.getChildren()) {
      templatesInFile.add(template.getTemplateName());
    }

    calleesNotInFile = new LinkedHashSet<>();
    visitChildren(node);
  }
72447
protected void callChildVisitors(XSLTVisitor visitor, boolean callAttrs)
    {
      int s = getImportCount();
      for (int j = 0; j < s; j++)
      {
      	getImport(j).callVisitors(visitor);
      }
   
      s = getIncludeCount();
      for (int j = 0; j < s; j++)
      {
      	getInclude(j).callVisitors(visitor);
      }

      s = getOutputCount();
      for (int j = 0; j < s; j++)
      {
        visitor.visitTopLevelInstruction(getOutput(j));
      }

      // Next, add in the attribute-set elements

      s = getAttributeSetCount();
      for (int j = 0; j < s; j++)
      {
      	ElemAttributeSet attrSet = getAttributeSet(j);
        if (visitor.visitTopLevelInstruction(attrSet))
        {
          attrSet.callChildVisitors(visitor);
        }
      }
      // Now the decimal-formats

      s = getDecimalFormatCount();
      for (int j = 0; j < s; j++)
      {
        visitor.visitTopLevelInstruction(getDecimalFormat(j));
      }

      // Now the keys

      s = getKeyCount();
      for (int j = 0; j < s; j++)
      {
        visitor.visitTopLevelInstruction(getKey(j));
      }

      // And the namespace aliases

      s = getNamespaceAliasCount();
      for (int j = 0; j < s; j++)
      {
        visitor.visitTopLevelInstruction(getNamespaceAlias(j));
      }

      // Next comes the templates

      s = getTemplateCount();
      for (int j = 0; j < s; j++)
      {
        try
        {
          ElemTemplate template = getTemplate(j);
          if (visitor.visitTopLevelInstruction(template))
          {
            template.callChildVisitors(visitor);
          }
        }
        catch (TransformerException te)
        {
          throw new org.apache.xml.utils.WrappedRuntimeException(te);
        }
      }

      // Then, the variables

      s = getVariableOrParamCount();
      for (int j = 0; j < s; j++)
      {
      	ElemVariable var = getVariableOrParam(j);
        if (visitor.visitTopLevelVariableOrParamDecl(var))
        {
          var.callChildVisitors(visitor);
        }
      }

      // And lastly the whitespace preserving and stripping elements

      s = getStripSpaceCount();
      for (int j = 0; j < s; j++)
      {
        visitor.visitTopLevelInstruction(getStripSpace(j));
      }

      s = getPreserveSpaceCount();
      for (int j = 0; j < s; j++)
      {
        visitor.visitTopLevelInstruction(getPreserveSpace(j));
      }
      
      if(null != m_NonXslTopLevel)
      {
      	java.util.Enumeration elements = m_NonXslTopLevel.elements();
      	while(elements.hasMoreElements())
      	{
      	  ElemTemplateElement elem = (ElemTemplateElement)elements.nextElement();
          if (visitor.visitTopLevelInstruction(elem))
          {
            elem.callChildVisitors(visitor);
          }
      		
      	}
      }
    }
1012337
private VariableDeclaration generateAccessorInterface(
      String className, TemplateElementNode node) {
    ImmutableList.Builder<MethodDeclaration> parameterMethods = ImmutableList.builder();
    for (TemplateParam param : node.getParams()) {
      parameterMethods.add(this.generateGetParamMethodForSoyElementClass(param, true));
    }

    ClassExpression soyElementClass =
        ClassExpression.create(ImmutableList.copyOf(parameterMethods.build()));
    VariableDeclaration classExpression =
        VariableDeclaration.builder(className)
            .setJsDoc(JsDoc.builder().addAnnotation("interface").build())
            .setRhs(soyElementClass)
            .build();
    return classExpression;
  }
1330170
private void processClasspath(String classpathElement) throws ResourceNotFoundException, ParseErrorException, Exception {
//        getLog().info("Classpath is " + classpathElement);
        if (classpathElement.endsWith(".jar")) {
            // TODO: implement JAR scanning
        } else {
            final File dir = new File(classpathElement);

            processPackage(dir, dir);
        }
    }
829696
public void addPathElement(QPathEntry element) {
       if (relPath == null)
          this.relPath = new QPath(new QPathEntry[]{element});
       else
          this.relPath = QPath.makeChildPath(relPath, element, element.getIndex());
    }
1349207
protected void callSubtreeVisitors(XPathVisitor visitor)
  {
    if (null != m_predicates)
    {
      int n = m_predicates.length;
      for (int i = 0; i < n; i++)
      {
        ExpressionOwner predOwner = new PredOwner(i);
        if (visitor.visitPredicate(predOwner, m_predicates[i]))
        {
          m_predicates[i].callVisitors(predOwner, visitor);
        }
      }
    }
    if (null != m_relativePathPattern)
    {
      m_relativePathPattern.callVisitors(this, visitor);
    }
  }
598290
@Override
  protected void visitSoyFileSetNode(SoyFileSetNode node) {
    for (SoyFileNode soyFile : node.getChildren()) {
      visit(soyFile);
    }
  }
189646
@Override
  protected void visitSoyNode(SoyNode node) {
    if (isComputableAsJsExprsVisitor.exec(node)) {
      // Simply generate JS expressions for this node and add them to the current output var.
      jsCodeBuilder.addChunksToOutputVar(genJsExprsVisitor.exec(node));

    } else {
      // Need to implement visit*Node() for the specific case.
      throw new UnsupportedOperationException("implement visit*Node for" + node.getKind());
    }
  }
801717
@Override
    public R visitPackage(PackageElement e, P p) {
        assert e.getKind() == PACKAGE: "Bad kind on PackageElement";
        return defaultAction(e, p);
    }
1308271
public static void generate(Elements elementUtils, Filer filer, SQLiteDatabaseSchema schema) throws IOException {
		String className = schema.getName();

		String dataSourceName = PREFIX + className;

		className = className.replaceAll(BindDataSourceBuilder.SUFFIX, SUFFIX);
		className = PREFIX + className;

		PackageElement pkg = elementUtils.getPackageOf(schema.getElement());
		String packageName = pkg.isUnnamed() ? "" : pkg.getQualifiedName().toString();

		AnnotationProcessorUtilis.infoOnGeneratedClasses(BindDataSource.class, packageName, className);

		//@formatter:off
		builder = TypeSpec.classBuilder(className).addModifiers(Modifier.PUBLIC).addModifiers(Modifier.ABSTRACT)
				.addTypeVariable(TypeVariableName.get("I"))
				.addTypeVariable(TypeVariableName.get("U"))
				.addTypeVariable(TypeVariableName.get("R"));
		//@formatter:on

		// javadoc
		builder.addJavadoc("\n<p>\nSpecialized async task to make async database operation on activity\n</p>\n");
		builder.addJavadoc("\n<p>\nUnlike standard async task, for an instance of this class can be used many time.\n</p>\n");
		builder.addJavadoc("\n<p>\nWhen method <code>execute</code> is invoked, an inner async task is created.\n</p>\n\n");
		JavadocUtility.generateJavadocGeneratedBy(builder);
		builder.addJavadoc("@param I input param\n");
		builder.addJavadoc("@param U update param\n");
		builder.addJavadoc("@param R result param\n\n");
		builder.addJavadoc("@see $T\n", className(className.replaceAll(SUFFIX, BindDaoFactoryBuilder.SUFFIX)));
		builder.addJavadoc("@see $T\n", className(dataSourceName));
		builder.addJavadoc("@see $T\n", BindAsyncTaskType.class);

		// build constructors
		builder.addMethod(MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC).addStatement("this($T.READ)", BindAsyncTaskType.class)
				.addJavadoc("<p>\nWith this constructor, a read only database connection will be used\n</p>\n").build());

		builder.addMethod(
				MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC).addJavadoc("<p>\nWith this constructor it is possible to specify which type of database use in async task\n</p>\n\n")
						.addJavadoc("@param mode allows to specify if and how open a data source connection\n").addParameter(BindAsyncTaskType.class, "mode").addCode("this.mode = mode;").build());

		// define fields
		{
			FieldSpec.Builder fieldSpec = FieldSpec.builder(BindAsyncTaskType.class, "mode", Modifier.PROTECTED);
			fieldSpec.addJavadoc("Allows to specify how async task interacts with data source.\n\n");
			builder.addField(fieldSpec.build());
		}

		{
			ParameterizedTypeName parameterizedTypeName = ParameterizedTypeName.get(TypeUtility.className(AsyncTask.class), TypeUtility.typeName("I"), TypeUtility.typeName("U"),
					TypeUtility.typeName("R"));
			FieldSpec.Builder fieldSpec = FieldSpec.builder(parameterizedTypeName, "asyncTask", Modifier.PROTECTED);
			fieldSpec.addJavadoc("Async task wrapped by this class\n\n");
			builder.addField(fieldSpec.build());
		}

		// build methods
		builder.addMethod(MethodSpec.methodBuilder("onPreExecute").addModifiers(Modifier.PUBLIC).addJavadoc("Use this method for operations on UI-thread before start execution\n").build());

		builder.addMethod(MethodSpec.methodBuilder("onExecute").returns(TypeUtility.typeName("R")).addParameter(TypeUtility.typeName(dataSourceName), "dataSource")
				.addJavadoc(
						"Method used to encapsulate operations on datasource\n\n@param dataSource\n\tuse it to retrieve DAO\n@return\n\tresult of operation (list, bean, etc) and execute transactions.\n")
				.addModifiers(Modifier.PUBLIC).addModifiers(Modifier.ABSTRACT).addException(Throwable.class).build());
		builder.addMethod(MethodSpec.methodBuilder("onFinish").addParameter(TypeUtility.typeName("R"), "result").addModifiers(Modifier.PUBLIC).addModifiers(Modifier.ABSTRACT)
				.addJavadoc("Use this method for operations on UI-thread after execution\n").build());

		builder.addMethod(MethodSpec.methodBuilder("onProgressUpdate").addModifiers(Modifier.PUBLIC).addParameter(ParameterSpec.builder(ArrayTypeName.of(TypeUtility.typeName("U")), "update").addAnnotation(AnnotationSpec.builder(SuppressWarnings.class).addMember("value", "$S", "unchecked").build()).build())
				.varargs().addJavadoc("Override this method to KRIPTON_DEBUG operation progress on UI-Thread\n").build());

		builder.addMethod(MethodSpec.methodBuilder("onError").addParameter(Throwable.class, "exception").addModifiers(Modifier.PUBLIC)
				.addJavadoc("This method is invoked when <code>onExecute</code> method generate an exception.\n@param exception exception generated\n")
				.addStatement("$T.error(exception.getMessage())", Logger.class).addStatement("exception.printStackTrace()").build());

		// method execute1
		{
			MethodSpec.Builder executeBuilder = MethodSpec.methodBuilder("execute")
					.addParameter(ParameterSpec.builder(ArrayTypeName.of(TypeUtility.className("I")), "params")
							.addAnnotation(AnnotationSpec.builder(SuppressWarnings.class).addMember("value", "$S", "unchecked").build()).build())
					.varargs(true).addModifiers(Modifier.PUBLIC).addJavadoc("Method to start operations.\n\n@param executor used executor\n@param data input\n");

			executeBuilder.addStatement("executeOnExecutor($T.SERIAL_EXECUTOR, params)", android.os.AsyncTask.class);
			builder.addMethod(executeBuilder.build());
		}

		// method execute2
		{
			MethodSpec.Builder executeBuilder = MethodSpec.methodBuilder("executeOnExecutor").addParameter(Executor.class, "executor")
					.addParameter(ParameterSpec.builder(ArrayTypeName.of(TypeUtility.className("I")), "params")
							.addAnnotation(AnnotationSpec.builder(SuppressWarnings.class).addMember("value", "$S", "unchecked").build()).build())
					.varargs(true).addModifiers(Modifier.PUBLIC).addJavadoc("Method to start operations.\n\n@param executor used executor\n@param data input\n");

		//@formatter:off
		TypeSpec.Builder anonymous = TypeSpec.anonymousClassBuilder("")
				.addSuperinterface(ParameterizedTypeName.get(TypeUtility.className(AsyncTask.class), TypeUtility.className("I"), TypeUtility.className("U"), TypeUtility.className("R")));
		anonymous.addMethod(MethodSpec.methodBuilder("onPreExecute").addModifiers(Modifier.PUBLIC).addAnnotation(Override.class).addStatement("$L.this.onPreExecute()",className).build());
		
		anonymous.addMethod(MethodSpec.methodBuilder("doInBackground").addModifiers(Modifier.PUBLIC).returns(TypeUtility.typeName("R")).addAnnotation(Override.class)
				.addParameter(ParameterSpec.builder(ArrayTypeName.of(TypeUtility.className("I")), "params")
						.addAnnotation(AnnotationSpec.builder(SuppressWarnings.class).addMember("value","$S", "unchecked").build())
						.build()).varargs(true)
				.addStatement("$L dataSource=$L.getInstance()", dataSourceName, dataSourceName)
				.addStatement("R result=null")
				.addStatement("boolean needToOpened=false")
				.addCode("if (mode==$T.READ) { needToOpened=true; dataSource.openReadOnlyDatabase(); } else if (mode==$T.READ_WRITE) { needToOpened=true; dataSource.openWritableDatabase();}\n", BindAsyncTaskType.class,BindAsyncTaskType.class)
				//.addStatement("$T sqlite=readOnlyTask ? dataSource.getReadableDatabase() : dataSource.getWritableDatabase()", SQLiteDatabase.class)
				.beginControlFlow("try")
				.addStatement("result=onExecute(dataSource)")
				.nextControlFlow("catch(Throwable e)")
					.addStatement("onError(e)")
				.nextControlFlow("finally")
					.beginControlFlow("if (needToOpened)")
					.addStatement("dataSource.close()")
					.endControlFlow()
				.endControlFlow()
				.addStatement("return result").build());
		
		anonymous.addMethod(MethodSpec.methodBuilder("onProgressUpdate")
				.addModifiers(Modifier.PUBLIC)
				.addAnnotation(Override.class)
				.addParameter(ParameterSpec.builder(ArrayTypeName.of(TypeUtility.className("U"))
						, "values")
						.addAnnotation(AnnotationSpec.builder(SuppressWarnings.class).addMember("value","$S", "unchecked").build())
						.build())
				.varargs(true)
				.addStatement("$L.this.onProgressUpdate(values)", className)
				.build());
		
		anonymous.addMethod(MethodSpec.methodBuilder("onPostExecute")
				.addModifiers(Modifier.PUBLIC)
				.addAnnotation(Override.class)
				.addParameter(ParameterSpec.builder(TypeUtility.className("R"), "result").build())
				.addStatement("$L.this.onFinish(result)",className)
				.build());
		//@formatter:on

		//@formatter:off
		executeBuilder.addStatement("asyncTask=$L", anonymous.build());		
		executeBuilder.addStatement("asyncTask.executeOnExecutor(executor, params)", anonymous.build());
		builder.addMethod(executeBuilder.build());		
					
		anonymous.addMethod(MethodSpec.methodBuilder("cancel")
				.addModifiers(Modifier.PUBLIC)
				.addModifiers(Modifier.FINAL)
				.addParameter(Boolean.TYPE, "mayInterruptIfRunning")
				.beginControlFlow("if (asyncTask!=null, args)")
				.addStatement("return asyncTask.cancel(mayInterruptIfRunning)")
				.endControlFlow()
				.addStatement("return false").build());
		}

		
		// build SimpleAsyncTask
		builder.addType(TypeSpec.classBuilder("Simple")
				.addJavadoc("Simple implementation of async task. It uses read only database.\n\n")
				.addJavadoc("@see $T\n", TypeUtility.typeName(className.replaceAll(SUFFIX, BindDaoFactoryBuilder.SUFFIX)))
				.addJavadoc("@see $T\n", TypeUtility.typeName(dataSourceName))
				.addModifiers(Modifier.PUBLIC)
				.addModifiers(Modifier.STATIC)
				.addModifiers(Modifier.ABSTRACT)
				.addTypeVariable(TypeVariableName.get("R"))
				.superclass(
						ParameterizedTypeName.get(TypeUtility.className(className),
								TypeUtility.className("Void"), 
								TypeUtility.className("Void"), 
								TypeUtility.className("R")
								)							
				)				
				.addMethod(MethodSpec.constructorBuilder()
						.addModifiers(Modifier.PUBLIC)
						.addJavadoc("Create an simple async task allowing user to decide which kind of operation can be done on datasource")
						.addParameter(BindAsyncTaskType.class, "mode")
						.addStatement("super(mode)").build())
				.addMethod(MethodSpec.constructorBuilder()
						.addModifiers(Modifier.PUBLIC)
						.addJavadoc("Create an simple async task for data source read only operation")
						.addStatement("super($T.READ)", BindAsyncTaskType.class).build())
				.build());		
		//@formatter:on

		TypeSpec typeSpec = builder.build();
		JavaWriterHelper.writeJava2File(filer, packageName, typeSpec);		
	}
754529
private static void appendSystemClasspath(JobConf conf,
                                            String pathSeparator,
                                            StringBuffer classPath) {
    // The alternate runtime can be used to debug tasks by putting a
    // custom version of the mapred libraries. This will get loaded before
    // the TT's jars.
    String debugRuntime = conf.get("mapred.task.debug.runtime.classpath");
    if (debugRuntime != null) {
      classPath.append(pathSeparator);
      classPath.append(debugRuntime);
    }
    // Determine system classpath for tasks. Default to tasktracker's
    // classpath.
    String systemClasspath = System.getenv(
      MAPREDUCE_TASK_SYSTEM_CLASSPATH_PROPERTY);
    if (systemClasspath == null) {
      systemClasspath = System.getProperty("java.class.path");
    }
    if (LOG.isDebugEnabled()) {
      LOG.debug("System classpath " + systemClasspath);
    }
    classPath.append(pathSeparator);
    classPath.append(systemClasspath);
  }
939623
function walkTree(element, context, mergeProps, visitor) {
  const Component = element.type;

  if (typeof Component === 'function') {

    const props = assign({}, Component.defaultProps, element.props, (mergeProps || {}));

    let childContext = context;
    let child;

    // Are we are a react class?
    // https://github.com/facebook/react/blob/master/src/renderers/shared/stack/reconciler/ReactCompositeComponent.js#L66
    if (Component.prototype && Component.prototype.isReactComponent) {

      const instance = new Component(props, context);

      // In case the user doesn't pass these to super in the constructor
      instance.props = instance.props || props;
      instance.context = instance.context || context;

   
      // Override setState to just change the state, not queue up an update.
      // We can't do the default React thing as we aren't mounted "properly"
      // however, we don't need to re-render as well only support setState in
      // componentWillMount, which happens *before* rendere.
      instance.setState = (newState) => {
        instance.state = assign({}, instance.state, newState);
      };

      // This is a poor man's version of
      // https://github.com/facebook/react/blob/master/src/renderers/shared/stack/reconciler/ReactCompositeComponent.js#L181
      if (instance.componentWillMount) {
        instance.componentWillMount();
      }

      if (instance.getChildContext) {
        childContext = assign({}, context, instance.getChildContext());
      }

      // Query we need to resolve first so stop traversing.
      if (visitor(element, instance, context) === false) {
        return;
      }

      child = instance.render();

    } else { // just a stateless functional

      // Query we need to resolve first so stop traversing.
      if (visitor(element, null, context) === false) {
        return;
      }

      child = Component(props, context);
    }


    if (child) {
      walkTree(child, childContext, null, visitor);
    }


  } else { // a basic string or dom element, just get children

    // Query we need to resolve first so stop traversing.
    if (visitor(element, null, context) === false) {
      return;
    }

    // Multiple children, traverse each one.
    if (element.props && element.props.children) {
      React.Children.forEach(element.props.children, (child) => {
        if (child) {
          walkTree(child, context, null, visitor);
        }
      });
    }
  }
}