(non-Javadoc)
@see backtype.storm.task.IBolt#prepare(java.util.Map, backtype.storm.task.TopologyContext, backtype.storm.task.OutputCollector)
488933
@Override
    public void prepare(Map stormConf, TopologyContext topologyContext, OutputCollector outputCollector) {
        this.outputCollector = outputCollector;
        this.client = clientFactory.makeClient(stormConf);
        this.queue = new LinkedBlockingQueue<>(QUEUE_MAX_SIZE);
    }
294932
@Override
	public void prepare(ResponseBuilder rb, ComponentFields mtasFields) throws IOException {
		mtasFields.doVersion = true;
		mtasFields.version = new ComponentVersion();
	}
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");
        }
      }
    }
  }
702598
def prepare(self):
        
        global print_prepare
        T = self.tm.trace
        if T: T.write(self.trace_message(u'Task.prepare()', self.node))

        # Now that it's the appropriate time, give the TaskMaster a
        # chance to raise any exceptions it encountered while preparing
        # this task.
        self.exception_raise()

        if self.tm.message:
            self.display(self.tm.message)
            self.tm.message = None

        # Let the targets take care of any necessary preparations.
        # This includes verifying that all of the necessary sources
        # and dependencies exist, removing the target file(s), etc.
        #
        # As of April 2008, the get_executor().prepare() method makes
        # sure that all of the aggregate sources necessary to build this
        # Task's target(s) exist in one up-front check.  The individual
        # target t.prepare() methods check that each target's explicit
        # or implicit dependencies exists, and also initialize the
        # .sconsign info.
        executor = self.targets[0].get_executor()
        if executor is None:
            return
        executor.prepare()
        for t in executor.get_action_targets():
            if print_prepare:
                print("Preparing target %s..."%t)
                for s in t.side_effects:
                    print("...with side-effect %s..."%s)
            t.prepare()
            for s in t.side_effects:
                if print_prepare:
                    print("...Preparing side-effect %s..."%s)
                s.prepare()
215525
public JsonObject prepareNewDefinitions() throws IOException {

		ObjectMapper mapper = JSonBindingUtils.createObjectMapper();
		StringWriter writer = new StringWriter();
		JsonObject newDef = new JsonObject();

		// Copy the test application here as test-jars cannot be referenced
		// in compile scope.
		Application app = newTestApplication();

		// Create a model, as complete as possible
		app.bindWithApplication( "externalExportPrefix1", "application 1" );
		app.bindWithApplication( "externalExportPrefix1", "application 2" );
		app.bindWithApplication( "externalExportPrefix2", "application 3" );

		app.setName( "My Application with special chàràcters" );
		app.getTemplate().externalExports.put( "internalGraphVariable", "variableAlias" );
		app.getTemplate().setExternalExportsPrefix( "externalExportPrefix" );
		app.getTemplate().setDescription( "some description" );

		// Serialize things and generate the examples
		// (*) Applications
		writer = new StringWriter();
		mapper.writeValue( writer, app );
		String s = writer.toString();
		convertToTypes( s, Application.class, newDef );

		// (*) Application Templates
		writer = new StringWriter();
		mapper.writeValue( writer, app.getTemplate());
		s = writer.toString();
		convertToTypes( s, ApplicationTemplate.class, newDef );

		// (*) Component
		Instance war = InstanceHelpers.findInstanceByPath( app, "/tomcat-vm/tomcat-server/hello-world" );
		Objects.requireNonNull( war );

		writer = new StringWriter();
		mapper.writeValue( writer, war.getComponent());
		s = writer.toString();
		convertToTypes( s, Component.class, newDef );

		// (*) Instance
		writer = new StringWriter();
		mapper.writeValue( writer, war );
		s = writer.toString();
		convertToTypes( s, Instance.class, newDef );

		// (*) Diagnostics
		Diagnostic diag = new Diagnostic( "/vm1/server1" );
		DependencyInformation di = new DependencyInformation( "facetOrComponentName", true, false );
		diag.getDependenciesInformation().add( di );

		writer = new StringWriter();
		mapper.writeValue( writer, diag );
		s = writer.toString();
		convertToTypes( s, Diagnostic.class, newDef );

		writer = new StringWriter();
		mapper.writeValue( writer, di );
		s = writer.toString();
		convertToTypes( s, DependencyInformation.class, newDef );

		// (*) Target descriptors
		TargetWrapperDescriptor twd = new TargetWrapperDescriptor();
		twd.setId( "target-id" );
		twd.setDescription( "some description" );
		twd.setHandler( "iaas-ec2" );
		twd.setName( "target name" );
		twd.setDefault( true );

		writer = new StringWriter();
		mapper.writeValue( writer, twd );
		s = writer.toString();
		convertToTypes( s, TargetWrapperDescriptor.class, newDef );

		// (*) Target usage items
		TargetUsageItem tui = new TargetUsageItem();
		tui.setName( "app or template name" );
		tui.setVersion( "template qualifier (null for applications)" );
		tui.setReferencing( true );
		tui.setUsing( true );

		writer = new StringWriter();
		mapper.writeValue( writer, tui );
		s = writer.toString();
		convertToTypes( s, TargetUsageItem.class, newDef );

		// (*) Target associations
		TargetAssociation ta = new TargetAssociation( "/vm-1", "VM", twd );

		writer = new StringWriter();
		mapper.writeValue( writer, ta );
		s = writer.toString();
		convertToTypes( s, TargetAssociation.class, newDef );

		// (*) Preferences
		Preference pref = new Preference( "key", "value", PreferenceKeyCategory.AUTONOMIC );

		writer = new StringWriter();
		mapper.writeValue( writer, pref );
		s = writer.toString();
		convertToTypes( s, Preference.class, newDef );

		// (*) Scheduled jobs
		ScheduledJob job = new ScheduledJob();
		job.setAppName( "application name" );
		job.setCmdName( "command name" );
		job.setCron( "0 0 12 ? * WED" );
		job.setJobId( "job-id" );
		job.setJobName( "job name" );

		writer = new StringWriter();
		mapper.writeValue( writer, job );
		s = writer.toString();
		convertToTypes( s, ScheduledJob.class, newDef );

		return newDef;
	}
67994
protected function prepare()
    {
        /** @var CollectionView $collection */
        $collection = $this->getComponent('collection_view');
        $collection->setData($this->getDataProvider());
        if ($collection->getDataInjector() === null) {
            $collection->setDataInjector($this->makeDataInjector());
        }
        $this->applyOperations();
        $this->hideSubmitButtonIfNotUsed();
    }
27932
public void prepare() {
        this.token_array = this.prepareTokenArray();
        SuffixData suffixData = SuffixArrays.createWithLCP(token_array, new SAIS(), comparator);
        this.suffix_array = suffixData.getSuffixArray();
        this.LCP_array = suffixData.getLCP();
        this.blocks = splitLCP_ArrayIntoIntervals();
        constructWitnessToBlockInstancesMap();
    }
425765
protected void doPrepare(Map<String, Object> topoConf, TopologyContext context, OutputCollector
      collector, Collection<Event<Tuple>> queue) {
    Objects.requireNonNull(topoConf);
    Objects.requireNonNull(context);
    Objects.requireNonNull(collector);
    Objects.requireNonNull(queue);
    this.windowedOutputCollector = new WindowedOutputCollector(collector);
    bolt.prepare(topoConf, context, windowedOutputCollector);
    this.listener = newWindowLifecycleListener();
    this.windowManager = initWindowManager(listener, topoConf, context, queue);
    start();
    LOG.info(String.format("Initialized window manager %s", windowManager));
  }
1002107
public void map(Object key, Object value, OutputCollector output, Reporter reporter) throws IOException {
    if (outerrThreadsThrowable != null) {
      mapRedFinished();
      throw new IOException ("MROutput/MRErrThread failed:"
                             + StringUtils.stringifyException(
                                                              outerrThreadsThrowable));
    }
    try {
      // 1/4 Hadoop in
      numRecRead_++;
      maybeLogRecord();
      if (debugFailDuring_ && numRecRead_ == 3) {
        throw new IOException("debugFailDuring_");
      }

      // 2/4 Hadoop to Tool
      if (numExceptions_ == 0) {
        if (!this.ignoreKey) {
          write(key);
          clientOut_.write(getInputSeparator());
        }
        write(value);
        if (!ignoreNewLine) {
          clientOut_.write('\n');
        }
        if(skipping) {
          //flush the streams on every record input if running in skip mode
          //so that we don't buffer other records surrounding a bad record. 
          clientOut_.flush();
        }
      } else {
        numRecSkipped_++;
      }
    } catch (IOException io) {
      numExceptions_++;
      if (numExceptions_ > 1 || numRecWritten_ < minRecWrittenToEnableSkip_) {
        // terminate with failure
        String msg = logFailure(io);
        appendLogToJobLog("failure");
        mapRedFinished();
        throw new IOException(msg);
      } else {
        // terminate with success:
        // swallow input records although the stream processor failed/closed
      }
    }
  }
174257
private void prepareCommand(final TaskInfo.Builder bldr, final SingularityTaskId taskId, final SingularityTaskRequest task, final SingularityOfferHolder offerHolder, final Optional<long[]> ports) {
    CommandInfo.Builder commandBldr = CommandInfo.newBuilder();

    Optional<String> specifiedUser = task.getPendingTask().getRunAsUserOverride().or(task.getDeploy().getUser());
    if (specifiedUser.isPresent()) {
      commandBldr.setUser(specifiedUser.get());
    }

    if (task.getDeploy().getCommand().isPresent()) {
      commandBldr.setValue(task.getDeploy().getCommand().get());
    }

    if (task.getDeploy().getArguments().isPresent()) {
      commandBldr.addAllArguments(task.getDeploy().getArguments().get());
    }

    if (task.getPendingTask().getCmdLineArgsList().isPresent()) {
      commandBldr.addAllArguments(task.getPendingTask().getCmdLineArgsList().get());
    }

    if (task.getDeploy().getShell().isPresent()){
      commandBldr.setShell(task.getDeploy().getShell().get());
    } else if ((task.getDeploy().getArguments().isPresent() && !task.getDeploy().getArguments().get().isEmpty()) ||
        // Hopefully temporary workaround for
        // http://www.mail-archive.com/user@mesos.apache.org/msg01449.html
        task.getDeploy().getContainerInfo().isPresent() ||
        (task.getPendingTask().getCmdLineArgsList().isPresent() && !task.getPendingTask().getCmdLineArgsList().get().isEmpty())) {
      commandBldr.setShell(false);
    }

    List<SingularityMesosArtifact> combinedArtifacts = new ArrayList<>();
    combinedArtifacts.addAll(task.getDeploy().getUris().or(Collections.emptyList()));
    combinedArtifacts.addAll(task.getPendingTask().getExtraArtifacts());

    prepareMesosUriDownloads(combinedArtifacts, commandBldr);

    prepareEnvironment(task, taskId, commandBldr, offerHolder, ports);

    bldr.setCommand(commandBldr);
  }
1271412
public static void marshallIntCollection(Collection<Integer> collection, ObjectOutput out) throws IOException {
      final int size = collection == null ? NULL_VALUE : collection.size();
      marshallSize(out, size);
      if (size <= 0) {
         return;
      }
      for (Integer integer : collection) {
         out.writeInt(integer);
      }
   }
78043
private void prepareJobInput(List<WorkUnit> workUnits) throws IOException {
    Closer closer = Closer.create();
    try {
      ParallelRunner parallelRunner = closer.register(new ParallelRunner(this.parallelRunnerThreads, this.fs));

      int multiTaskIdSequence = 0;
      // Serialize each work unit into a file named after the task ID
      for (WorkUnit workUnit : workUnits) {

        String workUnitFileName;
        if (workUnit instanceof MultiWorkUnit) {
          workUnitFileName = JobLauncherUtils.newMultiTaskId(this.jobContext.getJobId(), multiTaskIdSequence++)
              + MULTI_WORK_UNIT_FILE_EXTENSION;
        } else {
          workUnitFileName = workUnit.getProp(ConfigurationKeys.TASK_ID_KEY) + WORK_UNIT_FILE_EXTENSION;
        }
        Path workUnitFile = new Path(this.jobInputPath, workUnitFileName);
        LOG.debug("Writing work unit file " + workUnitFileName);

        parallelRunner.serializeToFile(workUnit, workUnitFile);

        // Append the work unit file path to the job input file
      }
    } catch (Throwable t) {
      throw closer.rethrow(t);
    } finally {
      closer.close();
    }
  }
189928
@Override
    public void prepare()
    {
        if (surface == null)
        {
            throw new LionEngineException(ERROR_SURFACE);
        }
        final Graphic g = surface.createGraphic();
        final int v = map.getInTileHeight();
        final int h = map.getInTileWidth();

        for (int ty = 0; ty < v; ty++)
        {
            for (int tx = 0; tx < h; tx++)
            {
                final Tile tile = map.getTile(tx, ty);
                final ColorRgba color = getTileColor(tile);
                if (!NO_TILE.equals(color))
                {
                    g.setColor(color);
                    g.drawRect(tx, v - ty - 1, 1, 1, true);
                }
            }
        }
        g.dispose();
    }
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;
	}
862865
private void prepareNextIterator()
	{
	    if (currentIterator == null || !currentIterator.hasNext())
	    {
	        currentIterator = null;
	        while (iteratorIterator.hasNext())
	        {
	            currentIterator = iteratorIterator.next();
	            if (currentIterator.hasNext())
	            {
	                break;
	            }
	            currentIterator = null;
	        }
	    }
	}
1063330
public void map(K1 arg0, V1 arg1, OutputCollector<Text, Text> arg2,
                  Reporter arg3) throws IOException {
    throw new IOException ("should not be called\n");
  }
246160
@SuppressWarnings("unchecked")
	public static <T> Collector<T> initOutputs(AbstractInvokable nepheleTask, ClassLoader cl, TaskConfig config,
					List<ChainedDriver<?, ?>> chainedTasksTarget, List<BufferWriter> eventualOutputs)
	throws Exception
	{
		final int numOutputs = config.getNumOutputs();

		// check whether we got any chained tasks
		final int numChained = config.getNumberOfChainedStubs();
		if (numChained > 0) {
			// got chained stubs. that means that this one may only have a single forward connection
			if (numOutputs != 1 || config.getOutputShipStrategy(0) != ShipStrategyType.FORWARD) {
				throw new RuntimeException("Plan Generation Bug: Found a chained stub that is not connected via an only forward connection.");
			}

			// instantiate each task
			@SuppressWarnings("rawtypes")
			Collector previous = null;
			for (int i = numChained - 1; i >= 0; --i)
			{
				// get the task first
				final ChainedDriver<?, ?> ct;
				try {
					Class<? extends ChainedDriver<?, ?>> ctc = config.getChainedTask(i);
					ct = ctc.newInstance();
				}
				catch (Exception ex) {
					throw new RuntimeException("Could not instantiate chained task driver.", ex);
				}

				// get the configuration for the task
				final TaskConfig chainedStubConf = config.getChainedStubConfig(i);
				final String taskName = config.getChainedTaskName(i);

				if (i == numChained -1) {
					// last in chain, instantiate the output collector for this task
					previous = getOutputCollector(nepheleTask, chainedStubConf, cl, eventualOutputs, chainedStubConf.getNumOutputs());
				}

				ct.setup(chainedStubConf, taskName, previous, nepheleTask, cl);
				chainedTasksTarget.add(0, ct);

				previous = ct;
			}
			// the collector of the first in the chain is the collector for the nephele task
			return (Collector<T>) previous;
		}
		// else

		// instantiate the output collector the default way from this configuration
		return getOutputCollector(nepheleTask , config, cl, eventualOutputs, numOutputs);
	}