Example #1
0
 /** Returns whether this JDBC data source can implement a given aggregate function. */
 private static boolean canImplement(SqlAggFunction aggregation, SqlDialect sqlDialect) {
   switch (sqlDialect.getDatabaseProduct()) {
     case MYSQL:
       return MYSQL_AGG_FUNCS.contains(aggregation);
     default:
       return AGG_FUNCS.contains(aggregation);
   }
 }
  /**
   * Get similarity of X submission to Y submission.
   *
   * @param xSubmission Submission to get similarities for
   * @param ySubmission Submission to get similarities relative to
   * @return Similarities of xSubmission to ySubmission
   * @throws NoSuchSubmissionException Thrown if either xSubmission or ySubmission are not present
   *     in the matrix
   */
  public AlgorithmResults getEntryFor(Submission xSubmission, Submission ySubmission)
      throws NoSuchSubmissionException {
    checkNotNull(xSubmission);
    checkNotNull(ySubmission);

    if (!xSubmissions.contains(xSubmission)) {
      throw new NoSuchSubmissionException(
          "X Submission with name " + xSubmission.getName() + " not found in similarity matrix!");
    } else if (!ySubmissions.contains(ySubmission)) {
      throw new NoSuchSubmissionException(
          "Y Submission with name " + ySubmission.getName() + " not found in similarity matrix!");
    }

    int xIndex = xSubmissions.indexOf(xSubmission);
    int yIndex = ySubmissions.indexOf(ySubmission);

    return entries[xIndex][yIndex];
  }
Example #3
0
  /**
   * Gets the context of this event within a stream
   *
   * @return the context in struct form
   */
  public StructDefinition getContext() {

    /* Most common case so far */
    if (fStreamContext == null) {
      return fEventContext;
    }

    /* streamContext is not null, but the context of the event is null */
    if (fEventContext == null) {
      return fStreamContext;
    }

    // TODO: cache if this is a performance issue

    /* The stream context and event context are assigned. */
    StructDeclaration mergedDeclaration = new StructDeclaration(1);

    Builder<String> builder = ImmutableList.<String>builder();
    List<Definition> fieldValues = new ArrayList<>();

    /* Add fields from the stream */
    for (String fieldName : fStreamContext.getFieldNames()) {
      Definition definition = fStreamContext.getDefinition(fieldName);
      mergedDeclaration.addField(fieldName, definition.getDeclaration());
      builder.add(fieldName);
      fieldValues.add(definition);
    }

    ImmutableList<String> fieldNames = builder.build();
    /*
     * Add fields from the event context, overwrite the stream ones if
     * needed.
     */
    for (String fieldName : fEventContext.getFieldNames()) {
      Definition definition = fEventContext.getDefinition(fieldName);
      mergedDeclaration.addField(fieldName, definition.getDeclaration());
      if (fieldNames.contains(fieldName)) {
        fieldValues.set((fieldNames.indexOf(fieldName)), definition);
      } else {
        builder.add(fieldName);
        fieldValues.add(definition);
      }
    }
    fieldNames = builder.build();
    StructDefinition mergedContext =
        new StructDefinition(
            mergedDeclaration,
            this,
            "context", //$NON-NLS-1$
            fieldNames,
            fieldValues.toArray(new Definition[fieldValues.size()]));
    return mergedContext;
  }
Example #4
0
 private ReferenceInfo newInfo(
     ColumnIdent column,
     DataType type,
     ColumnPolicy columnPolicy,
     ReferenceInfo.IndexType indexType) {
   RowGranularity granularity = RowGranularity.DOC;
   if (partitionedBy.contains(column)) {
     granularity = RowGranularity.PARTITION;
   }
   return new ReferenceInfo(
       new ReferenceIdent(ident, column), granularity, type, columnPolicy, indexType);
 }
  private void addToolchainFlags(List<String> argv) {
    boolean fullyStatic = (linkStaticness == LinkStaticness.FULLY_STATIC);
    boolean mostlyStatic = (linkStaticness == LinkStaticness.MOSTLY_STATIC);
    boolean sharedLinkopts =
        linkTargetType == LinkTargetType.DYNAMIC_LIBRARY
            || linkopts.contains("-shared")
            || cppConfiguration.getLinkOptions().contains("-shared");

    /*
     * For backwards compatibility, linkopts come _after_ inputFiles.
     * This is needed to allow linkopts to contain libraries and
     * positional library-related options such as
     *    -Wl,--begin-group -lfoo -lbar -Wl,--end-group
     * or
     *    -Wl,--as-needed -lfoo -Wl,--no-as-needed
     *
     * As for the relative order of the three different flavours of linkopts
     * (global defaults, per-target linkopts, and command-line linkopts),
     * we have no idea what the right order should be, or if anyone cares.
     */
    argv.addAll(linkopts);
    // Extra toolchain link options based on the output's link staticness.
    if (fullyStatic) {
      argv.addAll(cppConfiguration.getFullyStaticLinkOptions(features, sharedLinkopts));
    } else if (mostlyStatic) {
      argv.addAll(cppConfiguration.getMostlyStaticLinkOptions(features, sharedLinkopts));
    } else {
      argv.addAll(cppConfiguration.getDynamicLinkOptions(features, sharedLinkopts));
    }

    // Extra test-specific link options.
    if (useTestOnlyFlags) {
      argv.addAll(cppConfiguration.getTestOnlyLinkOptions());
    }

    argv.addAll(cppConfiguration.getLinkOptions());

    // -pie is not compatible with shared and should be
    // removed when the latter is part of the link command. Should we need to further
    // distinguish between shared libraries and executables, we could add additional
    // command line / CROSSTOOL flags that distinguish them. But as long as this is
    // the only relevant use case we're just special-casing it here.
    if (linkTargetType == LinkTargetType.DYNAMIC_LIBRARY) {
      Iterables.removeIf(argv, Predicates.equalTo("-pie"));
    }

    // Fission mode: debug info is in .dwo files instead of .o files. Inform the linker of this.
    if (!linkTargetType.isStaticLibraryLink() && cppConfiguration.useFission()) {
      argv.add("-Wl,--gdb-index");
    }
  }
 public boolean isTypeVariableInScope(String tvar) {
   if (typeParameters != null && typeParameters.contains(tvar)) {
     return true;
   }
   // We don't look at this.nominalType, b/c if this function is a generic
   // constructor, then typeParameters contains the relevant type variables.
   if (receiverType != null && receiverType.isUninstantiatedGenericType()) {
     RawNominalType rawType = receiverType.getRawNominalType();
     if (rawType.getTypeParameters().contains(tvar)) {
       return true;
     }
   }
   return false;
 }
Example #7
0
 private void add(
     ColumnIdent column,
     DataType type,
     ColumnPolicy columnPolicy,
     ReferenceInfo.IndexType indexType,
     boolean partitioned) {
   ReferenceInfo info = newInfo(column, type, columnPolicy, indexType);
   // don't add it if there is a partitioned equivalent of this column
   if (partitioned || !(partitionedBy != null && partitionedBy.contains(column))) {
     if (info.ident().isColumn()) {
       columnsBuilder.add(info);
     }
     referencesBuilder.put(info.ident().columnIdent(), info);
   }
   if (partitioned) {
     partitionedByColumnsBuilder.add(info);
   }
 }
  public static Map<String, BeanProperty> getNotNullValues(
      Class<? extends AbstractEntity> entityClass, AbstractDto dto) {

    try {

      List<String> entityFields = new ArrayList<String>();
      Class beanClass = getOriginalClassFromJavassist(entityClass);
      for (Field fd : beanClass.getDeclaredFields()) {
        entityFields.add(fd.getName());
      }

      HashMap<String, BeanProperty> mp = new HashMap<String, BeanProperty>();

      Field[] fds = getOriginalClassFromJavassist(dto).getDeclaredFields();
      for (Field fd : fds) {
        fd.setAccessible(true);
        if (!invalids.contains(fd.getName())) {

          Object value = Property.getPropertyValue(dto, fd.getName());

          if (value != null) {

            System.out.println(fd.getName() + "|" + fd.getType() + "|" + value);

            if (fd.isAnnotationPresent(PropertyMap.class)) {
              String entityPropName = fd.getAnnotation(PropertyMap.class).propertyName();
              if (entityFields.contains(entityPropName)) {
                mp.put(fd.getName(), new BeanProperty(entityPropName, fd.getType(), value));
              }
            } else {
              if (entityFields.contains(fd.getName())) {
                mp.put(fd.getName(), new BeanProperty(fd.getName(), fd.getType(), value));
              }
            }
          }
        }
      }
      return mp;
    } catch (Throwable e) {
      e.printStackTrace();
      return null;
    }
  }
  // merge the optionally existing xmlDocument with a lower priority xml file.
  private Optional<XmlDocument> merge(
      Optional<XmlDocument> xmlDocument,
      LoadedManifestInfo lowerPriorityDocument,
      MergingReport.Builder mergingReportBuilder)
      throws MergeFailureException {

    MergingReport.Result validationResult =
        PreValidator.validate(mergingReportBuilder, lowerPriorityDocument.getXmlDocument());
    if (validationResult == MergingReport.Result.ERROR) {
      mergingReportBuilder.addMessage(
          lowerPriorityDocument.getXmlDocument().getSourceLocation(),
          0,
          0,
          MergingReport.Record.Severity.ERROR,
          "Validation failed, exiting");
      return Optional.absent();
    }
    Optional<XmlDocument> result;
    if (xmlDocument.isPresent()) {
      result =
          xmlDocument.get().merge(lowerPriorityDocument.getXmlDocument(), mergingReportBuilder);
    } else {
      mergingReportBuilder
          .getActionRecorder()
          .recordDefaultNodeAction(lowerPriorityDocument.getXmlDocument().getRootNode());
      result = Optional.of(lowerPriorityDocument.getXmlDocument());
    }

    // if requested, dump each intermediary merging stage into the report.
    if (mOptionalFeatures.contains(Invoker.Feature.KEEP_INTERMEDIARY_STAGES)
        && result.isPresent()) {
      mergingReportBuilder.addMergingStage(result.get().prettyPrint());
    }

    return result;
  }
  private void generateSingleMLBytecodeCompilation(
      Map<Path, ImmutableSortedSet<BuildRule>> sourceToRule,
      ImmutableList.Builder<SourcePath> cmoFiles,
      Path mlSource,
      ImmutableMap<Path, ImmutableList<Path>> sources,
      ImmutableList<Path> cycleDetector) {

    ImmutableList<Path> newCycleDetector =
        ImmutableList.<Path>builder().addAll(cycleDetector).add(mlSource).build();

    if (cycleDetector.contains(mlSource)) {
      throw new HumanReadableException(
          "Dependency cycle detected: %s", Joiner.on(" -> ").join(newCycleDetector));
    }
    if (sourceToRule.containsKey(mlSource)) {
      return;
    }

    ImmutableSortedSet.Builder<BuildRule> depsBuilder = ImmutableSortedSet.naturalOrder();
    if (sources.containsKey(mlSource)) {
      for (Path dep : checkNotNull(sources.get(mlSource))) {
        generateSingleMLBytecodeCompilation(sourceToRule, cmoFiles, dep, sources, newCycleDetector);
        depsBuilder.addAll(checkNotNull(sourceToRule.get(dep)));
      }
    }
    ImmutableSortedSet<BuildRule> deps = depsBuilder.build();

    String name = mlSource.toFile().getName();
    BuildTarget buildTarget = createMLBytecodeCompileBuildTarget(params.getBuildTarget(), name);

    BuildRuleParams compileParams =
        params.copyWithChanges(
            buildTarget,
            Suppliers.ofInstance(
                ImmutableSortedSet.<BuildRule>naturalOrder()
                    .addAll(params.getDeclaredDeps().get())
                    .addAll(deps)
                    .addAll(ocamlContext.getBytecodeCompileDeps())
                    .build()),
            params.getExtraDeps());

    String outputFileName = getMLBytecodeOutputName(name);
    Path outputPath = ocamlContext.getCompileBytecodeOutputDir().resolve(outputFileName);
    final ImmutableList<String> compileFlags =
        getCompileFlags(/* isBytecode */ true, /* excludeDeps */ false);
    BuildRule compileBytecode =
        new OCamlMLCompile(
            compileParams,
            pathResolver,
            new OCamlMLCompileStep.Args(
                cCompiler.getEnvironment(pathResolver),
                cCompiler.getCommandPrefix(pathResolver),
                ocamlContext.getOcamlBytecodeCompiler().get(),
                outputPath,
                mlSource,
                compileFlags));
    resolver.addToIndex(compileBytecode);
    sourceToRule.put(
        mlSource,
        ImmutableSortedSet.<BuildRule>naturalOrder().add(compileBytecode).addAll(deps).build());
    if (!outputFileName.endsWith(OCamlCompilables.OCAML_CMI)) {
      cmoFiles.add(new BuildTargetSourcePath(compileBytecode.getBuildTarget()));
    }
  }
Example #11
0
 @Override
 public boolean contains(@Nullable Object object) {
   return forwardList.contains(object);
 }
  /**
   * Perform high level ordering of files merging and delegates actual merging to {@link
   * XmlDocument#merge(XmlDocument, com.android.manifmerger.MergingReport.Builder)}
   *
   * @return the merging activity report.
   * @throws MergeFailureException if the merging cannot be completed (for instance, if xml files
   *     cannot be loaded).
   */
  private MergingReport merge() throws MergeFailureException {
    // initiate a new merging report
    MergingReport.Builder mergingReportBuilder = new MergingReport.Builder(mLogger);

    SelectorResolver selectors = new SelectorResolver();
    // load all the libraries xml files up front to have a list of all possible node:selector
    // values.
    List<LoadedManifestInfo> loadedLibraryDocuments =
        loadLibraries(selectors, mergingReportBuilder);

    // load the main manifest file to do some checking along the way.
    LoadedManifestInfo loadedMainManifestInfo =
        load(
            new ManifestInfo(
                mManifestFile.getName(),
                mManifestFile,
                XmlDocument.Type.MAIN,
                Optional.<String>absent() /* mainManifestPackageName */),
            selectors,
            mergingReportBuilder);

    // first do we have a package declaration in the main manifest ?
    Optional<XmlAttribute> mainPackageAttribute =
        loadedMainManifestInfo.getXmlDocument().getPackage();
    if (!mainPackageAttribute.isPresent()) {
      mergingReportBuilder.addMessage(
          loadedMainManifestInfo.getXmlDocument().getSourceLocation(),
          0,
          0,
          MergingReport.Record.Severity.ERROR,
          String.format(
              "Main AndroidManifest.xml at %1$s manifest:package attribute " + "is not declared",
              loadedMainManifestInfo.getXmlDocument().getSourceLocation().print(true)));
      return mergingReportBuilder.build();
    }

    // check for placeholders presence.
    Map<String, Object> finalPlaceHolderValues = mPlaceHolderValues;
    if (!mPlaceHolderValues.containsKey(APPLICATION_ID)) {
      finalPlaceHolderValues =
          ImmutableMap.<String, Object>builder()
              .putAll(mPlaceHolderValues)
              .put(PACKAGE_NAME, mainPackageAttribute.get().getValue())
              .put(APPLICATION_ID, mainPackageAttribute.get().getValue())
              .build();
    }

    // perform system property injection
    performSystemPropertiesInjection(mergingReportBuilder, loadedMainManifestInfo.getXmlDocument());

    // force the re-parsing of the xml as elements may have been added through system
    // property injection.
    loadedMainManifestInfo =
        new LoadedManifestInfo(
            loadedMainManifestInfo,
            loadedMainManifestInfo.getOriginalPackageName(),
            loadedMainManifestInfo.getXmlDocument().reparse());

    // invariant : xmlDocumentOptional holds the higher priority document and we try to
    // merge in lower priority documents.
    Optional<XmlDocument> xmlDocumentOptional = Optional.absent();
    for (File inputFile : mFlavorsAndBuildTypeFiles) {
      mLogger.info("Merging flavors and build manifest %s \n", inputFile.getPath());
      LoadedManifestInfo overlayDocument =
          load(
              new ManifestInfo(
                  null,
                  inputFile,
                  XmlDocument.Type.OVERLAY,
                  Optional.of(mainPackageAttribute.get().getValue())),
              selectors,
              mergingReportBuilder);

      // check package declaration.
      Optional<XmlAttribute> packageAttribute = overlayDocument.getXmlDocument().getPackage();
      // if both files declare a package name, it should be the same.
      if (loadedMainManifestInfo.getOriginalPackageName().isPresent()
          && packageAttribute.isPresent()
          && !loadedMainManifestInfo
              .getOriginalPackageName()
              .get()
              .equals(packageAttribute.get().getValue())) {
        // no suggestion for library since this is actually forbidden to change the
        // the package name per flavor.
        String message =
            mMergeType == MergeType.APPLICATION
                ? String.format(
                    "Overlay manifest:package attribute declared at %1$s value=(%2$s)\n"
                        + "\thas a different value=(%3$s) "
                        + "declared in main manifest at %4$s\n"
                        + "\tSuggestion: remove the overlay declaration at %5$s "
                        + "\tand place it in the build.gradle:\n"
                        + "\t\tflavorName {\n"
                        + "\t\t\tapplicationId = \"%2$s\"\n"
                        + "\t\t}",
                    packageAttribute.get().printPosition(),
                    packageAttribute.get().getValue(),
                    mainPackageAttribute.get().getValue(),
                    mainPackageAttribute.get().printPosition(),
                    packageAttribute.get().getSourceLocation().print(true))
                : String.format(
                    "Overlay manifest:package attribute declared at %1$s value=(%2$s)\n"
                        + "\thas a different value=(%3$s) "
                        + "declared in main manifest at %4$s",
                    packageAttribute.get().printPosition(),
                    packageAttribute.get().getValue(),
                    mainPackageAttribute.get().getValue(),
                    mainPackageAttribute.get().printPosition());
        mergingReportBuilder.addMessage(
            overlayDocument.getXmlDocument().getSourceLocation(),
            0,
            0,
            MergingReport.Record.Severity.ERROR,
            message);
        return mergingReportBuilder.build();
      }

      overlayDocument
          .getXmlDocument()
          .getRootNode()
          .getXml()
          .setAttribute("package", mainPackageAttribute.get().getValue());
      xmlDocumentOptional = merge(xmlDocumentOptional, overlayDocument, mergingReportBuilder);

      if (!xmlDocumentOptional.isPresent()) {
        return mergingReportBuilder.build();
      }
    }

    mLogger.info("Merging main manifest %s\n", mManifestFile.getPath());
    xmlDocumentOptional = merge(xmlDocumentOptional, loadedMainManifestInfo, mergingReportBuilder);

    if (!xmlDocumentOptional.isPresent()) {
      return mergingReportBuilder.build();
    }

    // force main manifest package into resulting merged file when creating a library manifest.
    if (mMergeType == MergeType.LIBRARY) {
      // extract the package name...
      String mainManifestPackageName =
          loadedMainManifestInfo.getXmlDocument().getRootNode().getXml().getAttribute("package");
      // save it in the selector instance.
      if (!Strings.isNullOrEmpty(mainManifestPackageName)) {
        xmlDocumentOptional
            .get()
            .getRootNode()
            .getXml()
            .setAttribute("package", mainManifestPackageName);
      }
    }
    for (LoadedManifestInfo libraryDocument : loadedLibraryDocuments) {
      mLogger.info("Merging library manifest " + libraryDocument.getLocation());
      xmlDocumentOptional = merge(xmlDocumentOptional, libraryDocument, mergingReportBuilder);
      if (!xmlDocumentOptional.isPresent()) {
        return mergingReportBuilder.build();
      }
    }

    // done with proper merging phase, now we need to trim unwanted elements, placeholder
    // substitution and system properties injection.
    ElementsTrimmer.trim(xmlDocumentOptional.get(), mergingReportBuilder);
    if (mergingReportBuilder.hasErrors()) {
      return mergingReportBuilder.build();
    }

    // do one last placeholder substitution, this is useful as we don't stop the build
    // when a library failed a placeholder substitution, but the element might have
    // been overridden so the problem was transient. However, with the final document
    // ready, all placeholders values must have been provided.
    KeyBasedValueResolver<String> placeHolderValueResolver =
        new MapBasedKeyBasedValueResolver<String>(finalPlaceHolderValues);
    PlaceholderHandler placeholderHandler = new PlaceholderHandler();
    placeholderHandler.visit(
        mMergeType, xmlDocumentOptional.get(), placeHolderValueResolver, mergingReportBuilder);
    if (mergingReportBuilder.hasErrors()) {
      return mergingReportBuilder.build();
    }

    // perform system property injection.
    performSystemPropertiesInjection(mergingReportBuilder, xmlDocumentOptional.get());

    XmlDocument finalMergedDocument = xmlDocumentOptional.get();
    PostValidator.validate(finalMergedDocument, mergingReportBuilder);
    if (mergingReportBuilder.hasErrors()) {
      finalMergedDocument
          .getRootNode()
          .addMessage(
              mergingReportBuilder,
              MergingReport.Record.Severity.WARNING,
              "Post merge validation failed");
    }

    // only remove tools annotations if we are packaging an application.
    if (mOptionalFeatures.contains(Invoker.Feature.REMOVE_TOOLS_DECLARATIONS)) {
      finalMergedDocument =
          ToolsInstructionsCleaner.cleanToolsReferences(finalMergedDocument, mLogger);
    }

    if (mOptionalFeatures.contains(Invoker.Feature.EXTRACT_FQCNS)) {
      extractFcqns(finalMergedDocument);
    }

    if (finalMergedDocument != null) {
      mergingReportBuilder.setMergedDocument(finalMergedDocument);
    }

    MergingReport mergingReport = mergingReportBuilder.build();
    StdLogger stdLogger = new StdLogger(StdLogger.Level.INFO);
    mergingReport.log(stdLogger);
    stdLogger.verbose(mergingReport.getMergedDocument().get().prettyPrint());

    if (mReportFile.isPresent()) {
      writeReport(mergingReport);
    }

    return mergingReport;
  }
 /** Returns whether this handler applies to the given parameter string. */
 @Override
 public boolean handles(String alias) {
   return aliases.contains(alias);
 }
  @Override
  public void leavingState(final State state) throws OperationException {
    final DateTime utcNow = pluginControlPaymentAutomatonRunner.getClock().getUTCNow();

    // Retrieve the associated payment transaction, if any
    PaymentTransactionModelDao paymentTransactionModelDaoCandidate = null;
    if (stateContext.getTransactionId() != null) {
      paymentTransactionModelDaoCandidate =
          paymentDao.getPaymentTransaction(
              stateContext.getTransactionId(), stateContext.getInternalCallContext());
      Preconditions.checkNotNull(
          paymentTransactionModelDaoCandidate,
          "paymentTransaction cannot be null for id " + stateContext.getTransactionId());
    } else if (stateContext.getPaymentTransactionExternalKey() != null) {
      final List<PaymentTransactionModelDao> paymentTransactionModelDaos =
          paymentDao.getPaymentTransactionsByExternalKey(
              stateContext.getPaymentTransactionExternalKey(),
              stateContext.getInternalCallContext());
      if (!paymentTransactionModelDaos.isEmpty()) {
        paymentTransactionModelDaoCandidate =
            paymentTransactionModelDaos.get(paymentTransactionModelDaos.size() - 1);
      }
    }
    final PaymentTransactionModelDao paymentTransactionModelDao =
        paymentTransactionModelDaoCandidate != null
                && TRANSIENT_TRANSACTION_STATUSES.contains(
                    paymentTransactionModelDaoCandidate.getTransactionStatus())
            ? paymentTransactionModelDaoCandidate
            : null;

    if (stateContext.getPaymentId() != null && stateContext.getPaymentExternalKey() == null) {
      final PaymentModelDao payment =
          paymentDao.getPayment(stateContext.getPaymentId(), stateContext.getInternalCallContext());
      Preconditions.checkNotNull(
          payment, "payment cannot be null for id " + stateContext.getPaymentId());
      stateContext.setPaymentExternalKey(payment.getExternalKey());
      stateContext.setPaymentMethodId(payment.getPaymentMethodId());
    } else if (stateContext.getPaymentExternalKey() == null) {
      stateContext.setPaymentExternalKey(UUIDs.randomUUID().toString());
    }

    if (paymentTransactionModelDao != null) {
      stateContext.setPaymentTransactionExternalKey(
          paymentTransactionModelDao.getTransactionExternalKey());
    } else if (stateContext.getPaymentTransactionExternalKey() == null) {
      stateContext.setPaymentTransactionExternalKey(UUIDs.randomUUID().toString());
    }

    if (stateContext.getPaymentMethodId() == null) {
      // Similar logic in PaymentAutomatonRunner
      stateContext.setPaymentMethodId(stateContext.getAccount().getPaymentMethodId());
    }

    if (state.getName().equals(initialState.getName())
        || state.getName().equals(retriedState.getName())) {
      try {
        final PaymentAttemptModelDao attempt;
        if (paymentTransactionModelDao != null
            && paymentTransactionModelDao.getAttemptId() != null) {
          attempt =
              pluginControlPaymentAutomatonRunner
                  .getPaymentDao()
                  .getPaymentAttempt(
                      paymentTransactionModelDao.getAttemptId(),
                      stateContext.getInternalCallContext());
          Preconditions.checkNotNull(
              attempt,
              "attempt cannot be null for id " + paymentTransactionModelDao.getAttemptId());
        } else {
          //
          // We don't serialize any properties at this stage to avoid serializing sensitive
          // information.
          // However, if after going through the control plugins, the attempt end up in RETRIED
          // state,
          // the properties will be serialized in the enteringState callback (any plugin that sets a
          // retried date is responsible to correctly remove sensitive information such as CVV, ...)
          //
          final byte[] serializedProperties =
              PluginPropertySerializer.serialize(ImmutableList.<PluginProperty>of());

          attempt =
              new PaymentAttemptModelDao(
                  stateContext.getAccount().getId(),
                  stateContext.getPaymentMethodId(),
                  utcNow,
                  utcNow,
                  stateContext.getPaymentExternalKey(),
                  stateContext.getTransactionId(),
                  stateContext.getPaymentTransactionExternalKey(),
                  transactionType,
                  initialState.getName(),
                  stateContext.getAmount(),
                  stateContext.getCurrency(),
                  stateContext.getPaymentControlPluginNames(),
                  serializedProperties);
          pluginControlPaymentAutomatonRunner
              .getPaymentDao()
              .insertPaymentAttemptWithProperties(attempt, stateContext.getInternalCallContext());
        }

        stateContext.setAttemptId(attempt.getId());
      } catch (final PluginPropertySerializerException e) {
        throw new OperationException(e);
      }
    }
  }