/*
(non-Javadoc)

@see
mtas.solr.handler.component.util.MtasSolrComponent#prepare(org.apache.solr.
handler.component.ResponseBuilder,
mtas.codec.util.CodecComponent.ComponentFields)
507712
public void prepare(ResponseBuilder rb, ComponentFields mtasFields)
      throws IOException {
    if (rb.req.getParams().getBool(PARAM_MTAS_STATS_POSITIONS, false)) {
      preparePositions(rb, mtasFields);
    }
    if (rb.req.getParams().getBool(PARAM_MTAS_STATS_TOKENS, false)) {
      prepareTokens(rb, mtasFields);
    }
    if (rb.req.getParams().getBool(PARAM_MTAS_STATS_SPANS, false)) {
      prepareSpans(rb, mtasFields);
    }
  }
1170978
protected void prepareIO() {
        // we assume that everything in ByteArray is in AMF3
        Input input = new Input(data);
        input.enforceAMF3();
        dataInput = new DataInput(input);
        Output output = new Output(data);
        output.enforceAMF3();
        dataOutput = new DataOutput(output);
    }
72522
public void fieldToData(ComponentCache componentCache, int iRowIndex, int iColumnIndex)
    {
        if (componentCache.m_rgcompoments[iColumnIndex] != null)
        {
            Object object = this.getModel().getValueAt(iRowIndex, iColumnIndex);
            String string = "";
            if (object != null)
                string = object.toString();
            if (componentCache.m_rgcompoments[iColumnIndex] instanceof JTextComponent)
                ((JTextComponent)componentCache.m_rgcompoments[iColumnIndex]).setText(string);
            else if (componentCache.m_rgcompoments[iColumnIndex] instanceof JCheckBox)
            {
                boolean bIsSelected = false;
                if (string != null) if (string.equals("1"))
                    bIsSelected = true;
                ((JCheckBox)componentCache.m_rgcompoments[iColumnIndex]).setSelected(bIsSelected);
            }
        }
    }
59787
@Override
	Map<String,String> prepareConfiguration( TargetHandlerParameters parameters, SSHClient ssh, File tmpDir )
	throws IOException {

		try {
			// Reset all the fields
			Map<String,String> keyToNewValue = new HashMap<> ();
			keyToNewValue.put( AGENT_APPLICATION_NAME, "" );
			keyToNewValue.put( AGENT_SCOPED_INSTANCE_PATH, "" );
			keyToNewValue.put( AGENT_DOMAIN, "" );
			keyToNewValue.put( AGENT_PARAMETERS, Constants.AGENT_RESET );

			return keyToNewValue;

		} finally {
			// Consider the IP as not used anymore, no matter what
			this.embedded.releaseIpAddress( this.ip );
		}
	}
1298291
@Override
	protected void preparePaintComponent(final Request request) {
		if (!isInitialised()) {
			MyDataBean myBean = new MyDataBean();
			myBean.setName("My Bean");

			myBean.addBean(new SomeDataBean("blah", "more blah"));
			myBean.addBean(new SomeDataBean());

			repeaterFields.setData(myBean);

			setInitialised(true);
		}
	}
1337575
@Override
	public void prepare(ResponseBuilder rb) throws IOException {
		// System.out
		// .println(System.nanoTime() + " - " + Thread.currentThread().getId()
		// + " - " + rb.req.getParams().getBool(ShardParams.IS_SHARD, false)
		// + " PREPARE " + rb.stage + " " + rb.req.getParamString());
		// always create status
		initializeRequestHandler(rb);
		MtasSolrStatus solrStatus = new MtasSolrStatus(rb.req.getOriginalParams().toQueryString(),
				rb.req.getParams().getBool(ShardParams.IS_SHARD, false), rb.shards, rb.rsp);
		rb.req.getContext().put(MtasSolrStatus.class, solrStatus);
		solrStatus.setStage(rb.stage);
		if (rb.req.getParams().getBool(PARAM_MTAS, false)) {
			try {
				// initialize
				mtasSolrResultMerge = new MtasSolrResultMerge();
				// prepare components
				ComponentFields mtasFields = new ComponentFields();
				// get settings version
				if (rb.req.getParams().getBool(MtasSolrComponentVersion.PARAM_MTAS_VERSION, false)) {
					searchVersion.prepare(rb, mtasFields);
				}
				// get settings status
				if (rb.req.getParams().getBool(MtasSolrComponentStatus.PARAM_MTAS_STATUS, false)) {
					searchStatus.prepare(rb, mtasFields);
					mtasFields.status.handler = requestHandlerName;
					if (mtasFields.status.key != null) {
						solrStatus.setKey(mtasFields.status.key);
					}
				}
				// now, register status
				registerStatus(solrStatus);
				// get settings document
				if (rb.req.getParams().getBool(MtasSolrComponentDocument.PARAM_MTAS_DOCUMENT, false)) {
					searchDocument.prepare(rb, mtasFields);
				}
				// get settings kwic
				if (rb.req.getParams().getBool(MtasSolrComponentKwic.PARAM_MTAS_KWIC, false)) {
					searchKwic.prepare(rb, mtasFields);
				}
				// get settings list
				if (rb.req.getParams().getBool(MtasSolrComponentList.PARAM_MTAS_LIST, false)) {
					searchList.prepare(rb, mtasFields);
				}
				// get settings group
				if (rb.req.getParams().getBool(MtasSolrComponentGroup.PARAM_MTAS_GROUP, false)) {
					searchGroup.prepare(rb, mtasFields);
				}
				// get settings termvector
				if (rb.req.getParams().getBool(MtasSolrComponentTermvector.PARAM_MTAS_TERMVECTOR, false)) {
					searchTermvector.prepare(rb, mtasFields);
				}
				// get settings prefix
				if (rb.req.getParams().getBool(MtasSolrComponentPrefix.PARAM_MTAS_PREFIX, false)) {
					searchPrefix.prepare(rb, mtasFields);
				}
				// get settings stats
				if (rb.req.getParams().getBool(MtasSolrComponentStats.PARAM_MTAS_STATS, false)) {
					searchStats.prepare(rb, mtasFields);
				}
				// get settings facet
				if (rb.req.getParams().getBool(MtasSolrComponentFacet.PARAM_MTAS_FACET, false)) {
					searchFacet.prepare(rb, mtasFields);
				}
				// get settings collection
				if (rb.req.getParams().getBool(MtasSolrComponentCollection.PARAM_MTAS_COLLECTION, false)) {
					searchCollection.prepare(rb, mtasFields);
				}
				rb.req.getContext().put(ComponentFields.class, mtasFields);
			} catch (ExitableDirectoryReader.ExitingReaderException e) {
				solrStatus.setError(e.getMessage());
			} catch (IOException e) {
				solrStatus.setError(e);
			} finally {
				checkStatus(solrStatus);
			}
		} else {
			// register and check status
			registerStatus(solrStatus);
			checkStatus(solrStatus);
		}
	}
804458
@Override
	public void prepare() {
		List<Log> logs = global.logs();
		Object parent = null;
		
		for (int i = logs.size() - 1; i >=0; i--) {
			if (logs.get(i).operation() != Log.Operation.GET) {
				parent = logs.get(i).entity();
				break;
			}
		}
		
		Lock lock = new Lock(global.id(), KeyFactory.createKeyString(
				Keys.create(Translation.toKind(parent.getClass()), Entities.keyValue(parent)), 
				Translation.TRANSACTION_KIND, 
				global.id()), new Date());
		datastore.put(local, Translation.toEntity(lock, Keys.create(
				Translation.toKind(entity.getClass()), Entities.keyValue(entity))));
		local.commit();
		this.lock = lock;
	}
442649
@PostConstruct
    public void prepare() {
        Preconditions.checkNotNull(messageSource, "MessageSource should not be null");
        LOGGER.info(this.getClass().getSimpleName() + " has been initialized properly");
        localeContext = LocaleUtil.parseLocale(locale);
    }
57781
private ComponentFields getMtasFields(ResponseBuilder rb) {
		return (ComponentFields) rb.req.getContext().get(ComponentFields.class);
	}
392042
@Override
    public MarkLogicTupleQuery prepareTupleQuery(String queryString) throws RepositoryException, MalformedQueryException {
        return prepareTupleQuery(QueryLanguage.SPARQL, queryString);
    }
1306315
public ClassFileBuilder prepare() throws SupportException {

        // Add a property to the reference for each primary key in the master
        List<StorableProperty> masterPkProps = new ArrayList<StorableProperty>
            (mMasterStorableInfo.getPrimaryKeyProperties().values());

        // Sort master primary keys, to ensure consistent behavior.
        Collections.sort(masterPkProps,
                         BeanComparator.forClass(StorableProperty.class).orderBy("name"));

        for (StorableProperty masterPkProp : masterPkProps) {
            // Some of them may have already been added as explicit
            // primary keys, to articulate sort direction.
            if (!mBuilder.hasProperty(masterPkProp.getName())) {
                addProperty(masterPkProp);
                // For non-unique indexes, *all* master pk properties are members of the
                // generated primary key, in order to support duplicates.
                if (!mIsUnique) {
                    mPrimaryKey.addProperty(masterPkProp.getName());
                    mExtraPkProps.add(masterPkProp.getName());
                }
            }
        }

        // Ensure that a version property exists in the index entry, if the
        // user storable had one.
        if (!mBuilder.isVersioned()) {
            StorableProperty versionProperty = mMasterStorableInfo.getVersionProperty();
            if (versionProperty != null) {
                addProperty(versionProperty);
            }
        }

        ClassFileBuilder cfg = mBuilder.prepare();
        addSpecialMethods(cfg.getClassFile());
        return cfg;
    }
727016
public void prepare(ResponseBuilder rb, ComponentFields mtasFields)
      throws IOException {
    // System.out.println(
    // "collection: " + System.nanoTime() + " - " +
    // Thread.currentThread().getId()
    // + " - " + rb.req.getParams().getBool("isShard", false) + " PREPARE "
    // + rb.stage + " " + rb.req.getParamString());
    Set<String> ids = MtasSolrResultUtil
        .getIdsFromParameters(rb.req.getParams(), PARAM_MTAS_COLLECTION);
    if (!ids.isEmpty()) {
      int tmpCounter = 0;
      String[] keys = new String[ids.size()];
      String[] versions = new String[ids.size()];
      String[] actions = new String[ids.size()];
      String[] fields = new String[ids.size()];
      String[] collectionIds = new String[ids.size()];
      String[] posts = new String[ids.size()];
      String[] urls = new String[ids.size()];
      String[] collections = new String[ids.size()];
      for (String id : ids) {
        actions[tmpCounter] = rb.req.getParams().get(PARAM_MTAS_COLLECTION + "."
            + id + "." + NAME_MTAS_COLLECTION_ACTION, null);
        keys[tmpCounter] = rb.req.getParams().get(
            PARAM_MTAS_COLLECTION + "." + id + "." + NAME_MTAS_COLLECTION_KEY,
            String.valueOf(tmpCounter)).trim();
        versions[tmpCounter] = rb.req.getParams().get(
            PARAM_MTAS_COLLECTION + "." + id + "." + NAME_MTAS_COLLECTION_VERSION,
            null);
        fields[tmpCounter] = rb.req.getParams().get(
            PARAM_MTAS_COLLECTION + "." + id + "." + NAME_MTAS_COLLECTION_FIELD,
            null);
        collectionIds[tmpCounter] = rb.req.getParams().get(
            PARAM_MTAS_COLLECTION + "." + id + "." + NAME_MTAS_COLLECTION_ID,
            null);
        posts[tmpCounter] = rb.req.getParams().get(
            PARAM_MTAS_COLLECTION + "." + id + "." + NAME_MTAS_COLLECTION_POST,
            null);
        urls[tmpCounter] = rb.req.getParams().get(
            PARAM_MTAS_COLLECTION + "." + id + "." + NAME_MTAS_COLLECTION_URL,
            null);
        collections[tmpCounter] = rb.req.getParams().get(PARAM_MTAS_COLLECTION
            + "." + id + "." + NAME_MTAS_COLLECTION_COLLECTION, null);
        // always id for post
        if (actions[tmpCounter] != null && (actions[tmpCounter]
            .equals(ComponentCollection.ACTION_POST)
            || actions[tmpCounter].equals(ComponentCollection.ACTION_IMPORT)
            || actions[tmpCounter].equals(ComponentCollection.ACTION_CREATE))) {
          if (collectionIds[tmpCounter] == null
              || collectionIds[tmpCounter].isEmpty()) {
            collectionIds[tmpCounter] = UUID.randomUUID().toString();
            ModifiableSolrParams changedParams = new ModifiableSolrParams(
                rb.req.getParams());
            changedParams.remove(PARAM_MTAS_COLLECTION + "." + id + "."
                + NAME_MTAS_COLLECTION_ID);
            changedParams.set(PARAM_MTAS_COLLECTION + "." + id + "."
                + NAME_MTAS_COLLECTION_ID, collectionIds[tmpCounter]);
            rb.req.setParams(changedParams);
          }
        }
        tmpCounter++;
      }
      mtasFields.doCollection = true;
      MtasSolrResultUtil.compareAndCheck(keys, actions,
          NAME_MTAS_COLLECTION_KEY, NAME_MTAS_COLLECTION_ACTION, true);
      MtasSolrResultUtil.compareAndCheck(keys, versions,
          NAME_MTAS_COLLECTION_KEY, NAME_MTAS_COLLECTION_VERSION, true);
      MtasSolrResultUtil.compareAndCheck(keys, fields, NAME_MTAS_COLLECTION_KEY,
          NAME_MTAS_COLLECTION_FIELD, false);
      MtasSolrResultUtil.compareAndCheck(keys, collectionIds,
          NAME_MTAS_COLLECTION_KEY, NAME_MTAS_COLLECTION_ID, false);
      MtasSolrResultUtil.compareAndCheck(keys, posts, NAME_MTAS_COLLECTION_KEY,
          NAME_MTAS_COLLECTION_POST, false);
      MtasSolrResultUtil.compareAndCheck(keys, urls, NAME_MTAS_COLLECTION_KEY,
          NAME_MTAS_COLLECTION_URL, false);
      MtasSolrResultUtil.compareAndCheck(keys, collections,
          NAME_MTAS_COLLECTION_KEY, NAME_MTAS_COLLECTION_COLLECTION, false);
      for (int i = 0; i < actions.length; i++) {
        if (actions[i] != null) {
          ComponentCollection componentCollection;
          switch (actions[i]) {
          case ComponentCollection.ACTION_LIST:
            componentCollection = new ComponentCollection(keys[i],
                ComponentCollection.ACTION_LIST);
            componentCollection.setListVariables();
            mtasFields.collection.add(componentCollection);
            break;
          case ComponentCollection.ACTION_CHECK:
            if (collectionIds[i] != null) {
              componentCollection = new ComponentCollection(keys[i],
                  ComponentCollection.ACTION_CHECK);
              componentCollection.setCheckVariables(collectionIds[i]);
              mtasFields.collection.add(componentCollection);
            } else {
              throw new IOException(
                  "no id defined for collection (" + actions[i] + ")");
            }
            break;
          case ComponentCollection.ACTION_GET:
            if (collectionIds[i] != null) {
              componentCollection = new ComponentCollection(keys[i],
                  ComponentCollection.ACTION_GET);
              componentCollection.setGetVariables(collectionIds[i]);
              mtasFields.collection.add(componentCollection);
            } else {
              throw new IOException(
                  "no id defined for collection (" + actions[i] + ")");
            }
            break;
          case ComponentCollection.ACTION_CREATE:
            if (collectionIds[i] == null) {
              collectionIds[i] = UUID.randomUUID().toString();
            }
            if (fields[i] != null) {
              Set<String> fieldList = new HashSet<>(
                  Arrays.asList(fields[i].split(",")));
              componentCollection = new ComponentCollection(keys[i],
                  ComponentCollection.ACTION_CREATE);
              componentCollection.setCreateVariables(collectionIds[i],
                  fieldList);
              mtasFields.doCollection = true;
              mtasFields.collection.add(componentCollection);
              rb.setNeedDocSet(true);
            } else {
              throw new IOException(
                  "no field defined for collection (" + actions[i] + ")");
            }
            break;
          case ComponentCollection.ACTION_POST:
            if (posts[i] != null) {
              componentCollection = new ComponentCollection(keys[i],
                  ComponentCollection.ACTION_POST);
              componentCollection.setPostVariables(collectionIds[i],
                  stringToStringValues(posts[i]), versions[i]);
              mtasFields.collection.add(componentCollection);
            } else {
              throw new IOException(
                  "no post defined for collection (" + actions[i] + ")");
            }
            break;
          case ComponentCollection.ACTION_IMPORT:
            if (urls[i] != null && collections[i] != null) {
              componentCollection = new ComponentCollection(keys[i],
                  ComponentCollection.ACTION_IMPORT);
              componentCollection.setImportVariables(collectionIds[i], urls[i],
                  collections[i]);
              mtasFields.collection.add(componentCollection);
            } else {
              throw new IOException(
                  "no url or collection defined for collection (" + actions[i]
                      + ")");
            }
            break;
          case ComponentCollection.ACTION_DELETE:
            if (collectionIds[i] != null) {
              componentCollection = new ComponentCollection(keys[i],
                  ComponentCollection.ACTION_DELETE);
              componentCollection.setDeleteVariables(collectionIds[i]);
              mtasFields.collection.add(componentCollection);
            } else {
              throw new IOException(
                  "no id defined for collection (" + actions[i] + ")");
            }
            break;
          case ComponentCollection.ACTION_EMPTY:
            componentCollection = new ComponentCollection(keys[i],
                ComponentCollection.ACTION_EMPTY);
            mtasFields.collection.add(componentCollection);
            break;
          default:
            throw new IOException(
                "unrecognized action '" + actions[i] + "' for collection");
          }
        } else {
          throw new IOException("no action defined for collection");
        }
      }
    }
  }
675258
private void _serializeComponent(Component c, StringBuilder sb, Set<Object> done) throws ConverterException {

	ComponentSpecificAccess cw = new ComponentSpecificAccess(Component.ACCESS_PRIVATE, c);

	sb.append(goIn());
	try {
	    sb.append("evaluateComponent(").append(QUOTE_CHR).append(c.getAbsName()).append(QUOTE_CHR).append(',').append(QUOTE_CHR).append(ComponentUtil.md5(c)).append(QUOTE_CHR)
		    .append(",{");
	}
	catch (Exception e) {
	    throw toConverterException(e);
	}

	boolean doIt = false;
	Object member;
	{

	    Iterator<Entry<Key, Object>> it = cw.entryIterator();
	    deep++;
	    Entry<Key, Object> e;
	    while (it.hasNext()) {
		e = it.next();
		member = e.getValue();
		if (member instanceof UDF) continue;
		if (doIt) sb.append(',');
		doIt = true;
		sb.append(QUOTE_CHR);
		sb.append(escape(e.getKey().getString()));
		sb.append(QUOTE_CHR);
		sb.append(':');
		_serialize(member, sb, done);
	    }
	    sb.append("}");
	    deep--;
	}
	{
	    boolean isPeristent = c.isPersistent();

	    ComponentScope scope = c.getComponentScope();
	    Iterator<Entry<Key, Object>> it = scope.entryIterator();
	    sb.append(",{");
	    deep++;
	    doIt = false;
	    Property p;
	    Boolean remotingFetch;
	    Struct props = ignoreRemotingFetch ? null : ComponentUtil.getPropertiesAsStruct(c, false);
	    Entry<Key, Object> e;
	    Key k;
	    while (it.hasNext()) {
		e = it.next();
		k = e.getKey();
		// String key=Caster.toString(it.next(),"");
		if (KeyConstants._THIS.equalsIgnoreCase(k)) continue;
		if (!ignoreRemotingFetch) {
		    p = (Property) props.get(k, null);
		    if (p != null) {
			remotingFetch = Caster.toBoolean(p.getDynamicAttributes().get(REMOTING_FETCH, null), null);
			if (remotingFetch == null) {
			    if (isPeristent && ORMUtil.isRelated(p)) continue;
			}
			else if (!remotingFetch.booleanValue()) continue;
		    }
		}

		member = e.getValue();
		if (member instanceof UDF) continue;
		if (doIt) sb.append(',');
		doIt = true;
		sb.append(QUOTE_CHR);
		sb.append(escape(k.getString()));
		sb.append(QUOTE_CHR);
		sb.append(':');
		_serialize(member, sb, done);
	    }
	    sb.append("}");
	    deep--;
	}

	sb.append(")");
	// sb.append("");
	// throw new ConverterException("can't serialize a component "+component.getDisplayName());
    }
1149064
private void distributedProcessFinish(ResponseBuilder rb,
      ComponentFields mtasFields) throws IOException {
    // rewrite

    Object mtasResponseRaw;
    if ((mtasResponseRaw = rb.rsp.getValues().get("mtas")) != null
        && mtasResponseRaw instanceof NamedList) {
      NamedList<Object> mtasResponse = (NamedList<Object>) mtasResponseRaw;
      Object mtasResponseTermvectorRaw;
      if ((mtasResponseTermvectorRaw = mtasResponse.get(NAME)) != null
          && mtasResponseTermvectorRaw instanceof ArrayList) {
        MtasSolrResultUtil.rewrite(
            (ArrayList<Object>) mtasResponseTermvectorRaw, searchComponent);
      }
    }
  }
229890
@SuppressWarnings("unchecked")
  public void distributedProcess(ResponseBuilder rb, ComponentFields mtasFields)
      throws IOException {
    // rewrite
    NamedList<Object> mtasResponse = null;
    try {
      mtasResponse = (NamedList<Object>) rb.rsp.getValues().get("mtas");
    } catch (ClassCastException e) {
      log.debug(e);
      mtasResponse = null;
    }
    if (mtasResponse != null) {
      ArrayList<Object> mtasResponseGroup;
      try {
        mtasResponseGroup = (ArrayList<Object>) mtasResponse.get(NAME);
        if (mtasResponseGroup != null) {
          MtasSolrResultUtil.rewrite(mtasResponseGroup, searchComponent);
        }
      } catch (ClassCastException e) {
        log.debug(e);
        mtasResponse.remove(NAME);
      }
    }
  }
541544
@Override
	public void prepare() throws Exception {
		TaskConfig config = this.taskContext.getTaskConfig();
		if (config.getDriverStrategy() != DriverStrategy.SORTED_GROUP_REDUCE) {
			throw new Exception("Unrecognized driver strategy for GroupReduce driver: " + config.getDriverStrategy().name());
		}
		this.serializer = this.taskContext.<IT>getInputSerializer(0).getSerializer();
		this.comparator = this.taskContext.getInputComparator(0);
		this.input = this.taskContext.getInput(0);
	}
655283
@Override
  public SimpleOrderedMap<Object> create(ComponentStats response,
      Boolean encode) throws IOException {
    if (response instanceof ComponentPosition) {
      return createPosition((ComponentPosition) response, encode);
    } else if (response instanceof ComponentToken) {
      return createToken((ComponentToken) response, encode);
    } else if (response instanceof ComponentSpan) {
      return createSpan((ComponentSpan) response, encode);
    } else {
      throw new IOException("incorrect type " + response.getClass());
    }
  }