Java Code Examples for org.apache.commons.lang3.tuple.Pair#getValue()

The following examples show how to use org.apache.commons.lang3.tuple.Pair#getValue() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: InfoSchemaRecordGenerator.java    From Bats with Apache License 2.0 6 votes vote down vote up
/**
 * Visit the tables in the given schema. The
 * @param  schemaPath  the path to the given schema
 * @param  schema  the given schema
 */
public void visitTables(String schemaPath, SchemaPlus schema) {
  final AbstractSchema drillSchema = schema.unwrap(AbstractSchema.class);
  for (Pair<String, ? extends Table> tableNameToTable : drillSchema.getTablesByNames(schema.getTableNames())) {
    final String tableName = tableNameToTable.getKey();
    final Table table = tableNameToTable.getValue();
    final TableType tableType = table.getJdbcTableType();
    // Visit the table, and if requested ...
    if(shouldVisitTable(schemaPath, tableName, tableType) && visitTable(schemaPath, tableName, table)) {
      // ... do for each of the table's fields.
      final RelDataType tableRow = table.getRowType(new JavaTypeFactoryImpl(DRILL_REL_DATATYPE_SYSTEM));
      for (RelDataTypeField field: tableRow.getFieldList()) {
        if (shouldVisitColumn(schemaPath, tableName, field.getName())) {
          visitField(schemaPath, tableName, field);
        }
      }
    }
  }
}
 
Example 2
Source File: RenderDroneAI.java    From PneumaticCraft with GNU General Public License v3.0 6 votes vote down vote up
public void update(){
    entityItem.age += 4;
    ChunkPosition lastPos = pos;
    pos = drone.getTargetedBlock();
    if(pos != null) {
        if(lastPos == null) {
            oldPos = pos;
        } else if(!pos.equals(lastPos)) {
            progress = 0;
            oldPos = lastPos;
        }
    } else {
        oldPos = null;
    }
    progress = Math.min((float)Math.PI, progress + 0.1F);

    Iterator<Pair<RenderCoordWireframe, Integer>> iterator = blackListWireframes.iterator();
    while(iterator.hasNext()) {
        Pair<RenderCoordWireframe, Integer> wireframe = iterator.next();
        wireframe.getKey().ticksExisted++;
        wireframe.setValue(wireframe.getValue() - 1);
        if(wireframe.getValue() <= 0) {
            iterator.remove();
        }
    }
}
 
Example 3
Source File: AutoScaleProcessor.java    From pravega with Apache License 2.0 6 votes vote down vote up
private void triggerScaleDown(String streamSegmentName, boolean silent) {
    Pair<Long, Long> pair = cache.getIfPresent(streamSegmentName);
    long lastRequestTs = 0;

    if (pair != null && pair.getValue() != null) {
        lastRequestTs = pair.getValue();
    }

    long timestamp = getTimeMillis();
    long requestId = requestIdGenerator.get();
    if (timestamp - lastRequestTs > configuration.getMuteDuration().toMillis()) {
        log.info(requestId, "sending request for scale down for {}", streamSegmentName);

        Segment segment = Segment.fromScopedName(streamSegmentName);
        AutoScaleEvent event = new AutoScaleEvent(segment.getScope(), segment.getStreamName(), segment.getSegmentId(),
                AutoScaleEvent.DOWN, timestamp, 0, silent, requestId);
        writeRequest(event, () -> {
            if (!silent) {
                // mute only scale downs
                cache.put(streamSegmentName, new ImmutablePair<>(0L, timestamp));
            }
        });
    }
}
 
Example 4
Source File: HBaseStore.java    From datacollector with Apache License 2.0 6 votes vote down vote up
public Optional<String> get(Pair<String, HBaseColumn> key) throws Exception {
  if (key.getKey().isEmpty()) {
    return Optional.absent();
  }
  Get g = new Get(Bytes.toBytes(key.getKey()));
  HBaseColumn hBaseColumn = key.getValue();

  if (hBaseColumn.getCf().isPresent() && hBaseColumn.getQualifier().isPresent()) {
    g.addColumn(hBaseColumn.getCf().get(), hBaseColumn.getQualifier().get());
  }
  if (hBaseColumn.getTimestamp().isPresent()) {
    g.setTimeStamp(hBaseColumn.getTimestamp().getAsLong());
  }

  Result result = hBaseProcessor.get(g);
  String value = getValue(hBaseColumn, result);
  return Optional.fromNullable(value);
}
 
Example 5
Source File: CurrencyActionCmds.java    From MantaroBot with GNU General Public License v3.0 6 votes vote down vote up
private void handleRodBreak(Item item, Context ctx, Player p, DBUser u, SeasonPlayer sp, boolean isSeasonal) {
    Pair<Boolean, Player> breakage = handleDurability(ctx, item, p, u, sp, isSeasonal);
    if (!breakage.getKey())
        return;

    //We need to get this again since reusing the old ones will cause :fire:
    Player pl = breakage.getValue();
    Inventory inv = pl.getInventory();

    if(u.getData().isAutoEquip() && inv.containsItem(item)) {
        u.getData().getEquippedItems().equipItem(item);
        inv.process(new ItemStack(item, -1));

        pl.save();
        u.save();

        ctx.sendLocalized("commands.fish.autoequip.success", EmoteReference.CORRECT, item.getName());
    }
}
 
Example 6
Source File: MtasUimaParser.java    From inception with Apache License 2.0 6 votes vote down vote up
private Range getRange(AnnotationFS aAnnotation)
{
    // Get begin of the first token. Special cases:
    // 1) if the first token starts after the first char. For example, when there's
    // a space or line break in the beginning of the document.
    // 2) if the last token ends before the last char. Same as above.
    Pair<AnnotationFS, Integer> beginToken;
    if (tokenBeginIndex.floorEntry(aAnnotation.getBegin()) == null) {
        beginToken = tokenBeginIndex.firstEntry().getValue();
    }
    else {
        beginToken = tokenBeginIndex.floorEntry(aAnnotation.getBegin()).getValue();
    }
    
    Pair<AnnotationFS, Integer> endToken;
    if (tokenEndIndex.ceilingEntry(aAnnotation.getEnd()) == null) {
        endToken = tokenEndIndex.lastEntry().getValue();
    }
    else {
        endToken = tokenEndIndex.ceilingEntry(aAnnotation.getEnd()).getValue();
    }
    return new Range(beginToken.getValue(), endToken.getValue(), beginToken.getKey().getBegin(),
            endToken.getKey().getEnd());
}
 
Example 7
Source File: LineageMap.java    From systemds with Apache License 2.0 6 votes vote down vote up
private Pair<String, LineageItem> cleanupInputLiterals(Pair<String, LineageItem> li, ExecutionContext ec) {
	LineageItem item = li.getValue();
	if( item.getInputs() == null )
		return li;
	// fix literals referring to variables (e.g., for/parfor loop variable)
	for(int i=0; i<item.getInputs().length; i++) {
		LineageItem tmp = item.getInputs()[i];
		if( tmp.getType() != LineageItemType.Literal)
			continue;
		//check if CPOperand is not a literal, w/o parsing
		if( tmp.getData().endsWith("false") ) {
			CPOperand cp = new CPOperand(tmp.getData());
			if( cp.getDataType().isScalar() ) {
				cp.setLiteral(ec.getScalarInput(cp));
				item.getInputs()[i] = getOrCreate(cp);
			}
		}
	}
	return li;
}
 
Example 8
Source File: VariantEvalReportWriter.java    From gatk with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Common utility to configure a GATKReportTable columns
 *
 * Sets the column names to the strat names in stratsAndStates for the primary key in table
 *
 * @param table
 * @param primaryKey
 * @param stratsAndStates
 */
private static void setStratificationColumns(final GATKReportTable table,
                                             final String primaryKey,
                                             final List<Pair<VariantStratifier, Object>> stratsAndStates) {
    table.set(primaryKey, table.getTableName(), table.getTableName());
    for ( final Pair<VariantStratifier, Object> stratAndState : stratsAndStates ) {
        final VariantStratifier vs = stratAndState.getKey();
        final String columnName = vs.getName();
        final Object strat = stratAndState.getValue();
        if ( columnName == null || strat == null )
            throw new GATKException("Unexpected null variant stratifier state at " + table + " key = " + primaryKey);
        table.set(primaryKey, columnName, strat);
    }
}
 
Example 9
Source File: LineageParser.java    From systemds with Apache License 2.0 5 votes vote down vote up
public static LineageItem parseLineageTrace(String str, String name) {
	ExecutionContext ec = ExecutionContextFactory.createContext();
	LineageItem li = null;
	Map<Long, LineageItem> map = new HashMap<>();
	
	for (String line : str.split("\\r?\\n")) {
		li = null;
		Map<String, String> tokens = lineageTraceTokenizer.tokenize(line);
		Long id = Long.valueOf(tokens.get("id"));
		LineageItem.LineageItemType type = LineageItemUtils.getType(tokens.get("type"));
		String representation = tokens.get("representation");
		
		switch (type) {
			case Creation:
				Instruction inst = InstructionParser.parseSingleInstruction(representation);
				if (!(inst instanceof LineageTraceable))
					throw new ParseException("Invalid Instruction (" + inst.getOpcode() + ") traced");
				Pair<String,LineageItem> item = ((LineageTraceable) inst).getLineageItem(ec);
				if (item == null)
					throw new ParseException("Instruction without output (" + inst.getOpcode() + ") not supported");
				
				li = new LineageItem(id, item.getValue());
				break;
			
			case Literal:
				li = new LineageItem(id, representation);
				break;
			
			case Instruction:
				li = parseLineageInstruction(id, representation, map, name);
				break;
			
			default:
				throw new ParseException("Invalid LineageItemType given");
		}
		map.put(id, li);
	}
	return li;
}
 
Example 10
Source File: AdminReservationManagerIntegrationTest.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
private Triple<Event, String, TicketReservation> performExistingCategoryTest(List<TicketCategoryModification> categories, boolean bounded,
                                                                             List<Integer> attendeesNr, boolean addSeatsIfNotAvailable, boolean expectSuccess,
                                                                             int reservedTickets, int expectedEventSeats) {
    assertEquals("Test error: categories' size must be equal to attendees' size", categories.size(), attendeesNr.size());
    Pair<Event, String> eventWithUsername = initEvent(categories, organizationRepository, userManager, eventManager, eventRepository);
    Event event = eventWithUsername.getKey();
    String username = eventWithUsername.getValue();
    DateTimeModification expiration = DateTimeModification.fromZonedDateTime(ZonedDateTime.now().plusDays(1));
    CustomerData customerData = new CustomerData("Integration", "Test", "[email protected]", "Billing Address", "reference", "en", "1234", "CH", null);
    Iterator<Integer> attendeesIterator = attendeesNr.iterator();
    List<TicketCategory> existingCategories = ticketCategoryRepository.findAllTicketCategories(event.getId());
    List<Attendee> allAttendees = new ArrayList<>();
    List<TicketsInfo> ticketsInfoList = existingCategories.stream()
        .map(existingCategory -> {
            Category category = new Category(existingCategory.getId(), existingCategory.getName(), existingCategory.getPrice());
            List<Attendee> attendees = generateAttendees(attendeesIterator.next());
            allAttendees.addAll(attendees);
            return new TicketsInfo(category, attendees, addSeatsIfNotAvailable, false);
        }).collect(toList());
    AdminReservationModification modification = new AdminReservationModification(expiration, customerData, ticketsInfoList, "en", false,false, null, null);

    if(reservedTickets > 0) {
        TicketReservationModification trm = new TicketReservationModification();
        trm.setAmount(reservedTickets);
        trm.setTicketCategoryId(existingCategories.get(0).getId());
        TicketReservationWithOptionalCodeModification r = new TicketReservationWithOptionalCodeModification(trm, Optional.empty());
        ticketReservationManager.createTicketReservation(event, Collections.singletonList(r), Collections.emptyList(), DateUtils.addDays(new Date(), 1), Optional.empty(), Locale.ENGLISH, false);
    }

    Result<Pair<TicketReservation, List<Ticket>>> result = adminReservationManager.createReservation(modification, event.getShortName(), username);
    if(expectSuccess) {
        validateSuccess(bounded, attendeesNr, event, username, existingCategories, result, allAttendees, expectedEventSeats, reservedTickets);
    } else {
        assertFalse(result.isSuccess());
        return null;
    }
    return Triple.of(eventWithUsername.getLeft(), eventWithUsername.getRight(), result.getData().getKey());
}
 
Example 11
Source File: BinaryDataAdapter.java    From geowave with Apache License 2.0 5 votes vote down vote up
@Override
public AdapterPersistenceEncoding encode(
    final Pair<byte[], byte[]> entry,
    final CommonIndexModel indexModel) {
  return new AdapterPersistenceEncoding(
      getDataId(entry),
      new MultiFieldPersistentDataset<>(),
      new SingleFieldPersistentDataset<>(SINGLETON_FIELD_NAME, entry.getValue()));
}
 
Example 12
Source File: ConservationMetrics.java    From RAMPART with GNU General Public License v3.0 5 votes vote down vote up
@Override
public double[] parseWeightings(List<Pair<String, Double>> list) {

    double[] weightings = new double[this.nbMetrics];

    for(Pair<String, Double> kv : list) {

        String key = kv.getKey();
        double value = kv.getValue();

        if (key.equalsIgnoreCase(M_NB_BASES)) {
            weightings[IDX_NB_BASES] = value;
        }
        else if (key.equalsIgnoreCase(M_NB_BASES_GT_1KB)) {
            weightings[IDX_NB_BASES_GT_1KB] = value;
        }
        else if (key.equalsIgnoreCase(M_GC_PERC)) {
            weightings[IDX_GC_PERC] = value;
        }
        else if (key.equalsIgnoreCase(M_NB_GENES)) {
            weightings[IDX_NB_GENES] = value;
        }
        else if (key.equalsIgnoreCase(M_CEG_COMPLETE)) {
            weightings[IDX_CEG_COMPLETE] = value;
        }
    }

    return weightings;
}
 
Example 13
Source File: ResourceId.java    From azure-cosmosdb-java with MIT License 5 votes vote down vote up
public static ResourceId parse(String id) throws IllegalArgumentException {
    Pair<Boolean, ResourceId> pair = ResourceId.tryParse(id);

    if (!pair.getKey()) {
        throw new IllegalArgumentException(String.format(
                "Invalid resource id %s", id));
    }
    return pair.getValue();
}
 
Example 14
Source File: PneumaticRecipeRegistry.java    From PneumaticCraft with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void registerHeatFrameCoolRecipe(Object input, ItemStack output){
    if(input == null) throw new NullPointerException("Input can't be null!");
    if(!(input instanceof ItemStack) && !(input instanceof Pair)) throw new IllegalArgumentException("Input needs to be of type ItemStack or (Apache's) Pair<String, Integer>. Violating object: " + input);
    if(input instanceof Pair) {
        Pair pair = (Pair)input;
        if(!(pair.getKey() instanceof String)) throw new IllegalArgumentException("Pair key needs to be a String (ore dict entry)");
        if(!(pair.getValue() instanceof Integer)) throw new IllegalArgumentException("Value key needs to be an Integer (amount)");
    }
    if(output == null) throw new NullPointerException("Output can't be null!");
    heatFrameCoolingRecipes.add(new ImmutablePair(input, output));
}
 
Example 15
Source File: ListMap.java    From recheck with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public V remove( final Object k1 ) {
	for ( int idx = 0; idx < mappings.size(); idx++ ) {
		final Pair<K, V> mapping = mappings.get( idx );
		final K k2 = mapping.getKey();
		if ( k1 == null && k2 == null || k2 != null && k2.equals( k1 ) ) {
			mappings.remove( idx );
			return mapping.getValue();
		}
	}
	return null;
}
 
Example 16
Source File: ContiguityMetrics.java    From RAMPART with GNU General Public License v3.0 5 votes vote down vote up
@Override
public double[] parseWeightings(List<Pair<String, Double>> list) {

    double[] weightings = new double[this.nbMetrics];

    for(Pair<String, Double> kv : list) {

        String key = kv.getKey();
        double value = kv.getValue();

        if (key.equalsIgnoreCase(M_NB_SEQS)) {
            weightings[IDX_NB_SEQS] = value;
        }
        else if (key.equalsIgnoreCase(M_NB_SEQS_GT_1KB)) {
            weightings[IDX_NB_SEQS_GT_1KB] = value;
        }
        else if (key.equalsIgnoreCase(M_MAX_LEN)) {
            weightings[IDX_MAX_LEN] = value;
        }
        else if (key.equalsIgnoreCase(M_N50)) {
            weightings[IDX_N50] = value;
        }
        else if (key.equalsIgnoreCase(M_NA50)) {
            weightings[IDX_NA50] = value;
        }
        else if (key.equalsIgnoreCase(M_L50)) {
            weightings[IDX_L50] = value;
        }
    }

    return weightings;
}
 
Example 17
Source File: DefaultExceptionContext.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Object getFirstContextValue(String label) {
    for (final Pair<String, Object> pair : contextValues) {
        if (StringUtils.equals(label, pair.getKey())) {
            return pair.getValue();
        }
    }
    return null;
}
 
Example 18
Source File: Driver.java    From esigate with Apache License 2.0 4 votes vote down vote up
/**
 * Perform rendering on a single url content, and append result to "writer". Automatically follows redirects
 * 
 * @param pageUrl
 *            Address of the page containing the template
 * @param incomingRequest
 *            originating request object
 * @param renderers
 *            the renderers to use in order to transform the output
 * @return The resulting response
 * @throws IOException
 *             If an IOException occurs while writing to the writer
 * @throws HttpErrorPage
 *             If an Exception occurs while retrieving the template
 */
public CloseableHttpResponse render(String pageUrl, IncomingRequest incomingRequest, Renderer... renderers)
        throws IOException, HttpErrorPage {
    DriverRequest driverRequest = new DriverRequest(incomingRequest, this, pageUrl);

    // Replace ESI variables in URL
    // TODO: should be performed in the ESI extension
    String resultingPageUrl = VariablesResolver.replaceAllVariables(pageUrl, driverRequest);

    String targetUrl = ResourceUtils.getHttpUrlWithQueryString(resultingPageUrl, driverRequest, false);

    String currentValue;
    CloseableHttpResponse response;

    // Retrieve URL
    // Get from cache to prevent multiple request to the same url if
    // multiple fragments are used.

    String cacheKey = CACHE_RESPONSE_PREFIX + targetUrl;
    Pair<String, CloseableHttpResponse> cachedValue = incomingRequest.getAttribute(cacheKey);

    // content and response were not in cache
    if (cachedValue == null) {
        OutgoingRequest outgoingRequest = requestExecutor.createOutgoingRequest(driverRequest, targetUrl, false);
        headerManager.copyHeaders(driverRequest, outgoingRequest);
        response = requestExecutor.execute(outgoingRequest);
        int redirects = MAX_REDIRECTS;
        try {
            while (redirects > 0
                    && this.redirectStrategy.isRedirected(outgoingRequest, response, outgoingRequest.getContext())) {

                // Must consume the entity
                EntityUtils.consumeQuietly(response.getEntity());

                redirects--;

                // Perform new request
                outgoingRequest =
                        this.requestExecutor.createOutgoingRequest(
                                driverRequest,
                                this.redirectStrategy.getLocationURI(outgoingRequest, response,
                                        outgoingRequest.getContext()).toString(), false);
                this.headerManager.copyHeaders(driverRequest, outgoingRequest);
                response = requestExecutor.execute(outgoingRequest);
            }
        } catch (ProtocolException e) {
            throw new HttpErrorPage(HttpStatus.SC_BAD_GATEWAY, "Invalid response from server", e);
        }
        response = this.headerManager.copyHeaders(outgoingRequest, incomingRequest, response);
        currentValue = HttpResponseUtils.toString(response, this.eventManager);
        // Cache
        cachedValue = new ImmutablePair<>(currentValue, response);
        incomingRequest.setAttribute(cacheKey, cachedValue);
    }
    currentValue = cachedValue.getKey();
    response = cachedValue.getValue();

    logAction("render", pageUrl, renderers);

    // Apply renderers
    currentValue = performRendering(pageUrl, driverRequest, response, currentValue, renderers);

    response.setEntity(new StringEntity(currentValue, HttpResponseUtils.getContentType(response)));

    return response;
}
 
Example 19
Source File: JobCoordinatorService.java    From feast with Apache License 2.0 4 votes vote down vote up
/**
 * Makes Job Update Tasks required to reconcile the current ingestion jobs with the given source
 * to store map. Compares the current ingestion jobs and source to store mapping to determine
 * which whether jobs have started/stopped/updated in terms of Job Update tasks. Only tries to
 * stop ingestion jobs its the required ingestions to maintained ingestion jobs are already
 * RUNNING.
 *
 * @param sourceToStores a iterable of source to stores pairs where ingestion jobs would have to
 *     be maintained for ingestion to work correctly.
 * @return list of job update tasks required to reconcile the current ingestion jobs to the state
 *     that is defined by sourceStoreMap.
 */
List<JobTask> makeJobUpdateTasks(Iterable<Pair<Source, Set<Store>>> sourceToStores) {
  List<JobTask> jobTasks = new LinkedList<>();
  // Ensure a running job for each source to store mapping
  List<Job> activeJobs = new LinkedList<>();
  boolean isSafeToStopJobs = true;

  for (Pair<Source, Set<Store>> mapping : sourceToStores) {
    Source source = mapping.getKey();
    Set<Store> stores = mapping.getValue();
    Set<FeatureSet> featureSets =
        stores.stream()
            .flatMap(s -> getFeatureSetsForStore(s).stream())
            .collect(Collectors.toSet());

    Job job = groupingStrategy.getOrCreateJob(source, stores);

    if (job.isDeployed()) {
      if (!job.isRunning()) {
        jobTasks.add(UpdateJobStatusTask.builder().setJob(job).setJobManager(jobManager).build());

        // Mark that it is not safe to stop jobs without disrupting ingestion
        isSafeToStopJobs = false;
        continue;
      }

      if (jobRequiresUpgrade(job, stores) && job.isRunning()) {
        // Since we want to upgrade job without downtime
        // it would make sense to spawn clone of current job
        // and terminate old version on the next Poll.
        // Both jobs should be in the same consumer group and not conflict with each other
        job = job.clone();
        job.setId(groupingStrategy.createJobId(job));
        job.setStores(stores);

        isSafeToStopJobs = false;

        jobTasks.add(CreateJobTask.builder().setJob(job).setJobManager(jobManager).build());
      } else {
        jobTasks.add(UpdateJobStatusTask.builder().setJob(job).setJobManager(jobManager).build());
      }
    } else {
      job.setId(groupingStrategy.createJobId(job));

      jobTasks.add(CreateJobTask.builder().setJob(job).setJobManager(jobManager).build());
    }

    allocateFeatureSets(job, featureSets);

    // Record the job as required to safeguard it from getting stopped
    activeJobs.add(job);
  }
  // Stop extra jobs that are not required to maintain ingestion when safe
  if (isSafeToStopJobs) {
    getExtraJobs(activeJobs)
        .forEach(
            extraJob -> {
              jobTasks.add(
                  TerminateJobTask.builder().setJob(extraJob).setJobManager(jobManager).build());
            });
  }

  return jobTasks;
}
 
Example 20
Source File: LuceneIndex.java    From titan1withtp3.1 with Apache License 2.0 4 votes vote down vote up
private void mutateStores(Map.Entry<String, Map<String, IndexMutation>> stores, KeyInformation.IndexRetriever informations) throws IOException, BackendException {
    IndexReader reader = null;
    try {
        String storename = stores.getKey();
        IndexWriter writer = getWriter(storename);
        reader = DirectoryReader.open(writer, true);
        IndexSearcher searcher = new IndexSearcher(reader);
        for (Map.Entry<String, IndexMutation> entry : stores.getValue().entrySet()) {
            String docid = entry.getKey();
            IndexMutation mutation = entry.getValue();

            if (mutation.isDeleted()) {
                if (log.isTraceEnabled())
                    log.trace("Deleted entire document [{}]", docid);

                writer.deleteDocuments(new Term(DOCID, docid));
                continue;
            }

            Pair<Document, Map<String, Shape>> docAndGeo = retrieveOrCreate(docid, searcher);
            Document doc = docAndGeo.getKey();
            Map<String, Shape> geofields = docAndGeo.getValue();

            Preconditions.checkNotNull(doc);
            for (IndexEntry del : mutation.getDeletions()) {
                Preconditions.checkArgument(!del.hasMetaData(), "Lucene index does not support indexing meta data: %s", del);
                String key = del.field;
                if (doc.getField(key) != null) {
                    if (log.isTraceEnabled())
                        log.trace("Removing field [{}] on document [{}]", key, docid);

                    doc.removeFields(key);
                    geofields.remove(key);
                }
            }

            addToDocument(storename, docid, doc, mutation.getAdditions(), geofields, informations);

            //write the old document to the index with the modifications
            writer.updateDocument(new Term(DOCID, docid), doc);
        }
        writer.commit();
    } finally {
        IOUtils.closeQuietly(reader);
    }
}