Java Code Examples for org.bson.Document#getString()

The following examples show how to use org.bson.Document#getString() . 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: MongoStorage.java    From LuckPerms with MIT License 6 votes vote down vote up
@Override
public <N extends Node> List<NodeEntry<String, N>> searchGroupNodes(ConstraintNodeMatcher<N> constraint) throws Exception {
    List<NodeEntry<String, N>> held = new ArrayList<>();
    MongoCollection<Document> c = this.database.getCollection(this.prefix + "groups");
    try (MongoCursor<Document> cursor = c.find().iterator()) {
        while (cursor.hasNext()) {
            Document d = cursor.next();
            String holder = d.getString("_id");

            Set<Node> nodes = new HashSet<>(nodesFromDoc(d));
            for (Node e : nodes) {
                N match = constraint.match(e);
                if (match != null) {
                    held.add(NodeEntry.of(holder, match));
                }
            }
        }
    }
    return held;
}
 
Example 2
Source File: MongoDBArtifactStore.java    From hawkbit-extensions with Eclipse Public License 1.0 6 votes vote down vote up
@SuppressWarnings("squid:S2589")
// False positive: file.getMetadata() can return null
private static final String getContentType(final GridFSFile file) {
    final Document metadata = file.getMetadata();
    String contentType = null;
    if (metadata != null) {
        contentType = metadata.getString(CONTENT_TYPE);
    }
    if (contentType == null) {
        try {
            contentType = file.getContentType();
        } catch (final MongoGridFSException e) {
            throw new ArtifactStoreException("Could not determine content type for file " + file.getId(), e);
        }
    }
    return contentType;
}
 
Example 3
Source File: IndexConfigUtil.java    From lumongo with Apache License 2.0 6 votes vote down vote up
private static AnalyzerSettings.Builder getAnalyzerSettings(Document analyzerSettingsDoc) {
	AnalyzerSettings.Builder analyzerSettings = AnalyzerSettings.newBuilder();

	String similarity = analyzerSettingsDoc.getString(SIMILARITY);
	if (similarity != null) {
		analyzerSettings.setSimilarity(AnalyzerSettings.Similarity.valueOf(similarity));
	}
	String tokenizer = analyzerSettingsDoc.getString(TOKENIZER);
	if (tokenizer != null) {
		analyzerSettings.setTokenizer(AnalyzerSettings.Tokenizer.valueOf(tokenizer));
	}

	String queryHandling = analyzerSettingsDoc.getString(QUERY_HANDLING);
	if (queryHandling != null) {
		analyzerSettings.setQueryHandling(AnalyzerSettings.QueryHandling.valueOf(queryHandling));
	}

	List<String> filters = (List<String>) analyzerSettingsDoc.get(FILTERS);
	if (filters != null) {
		for (String filter : filters) {
			analyzerSettings.addFilter(AnalyzerSettings.Filter.valueOf(filter));
		}
	}
	return analyzerSettings;
}
 
Example 4
Source File: OneM2MDmController.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public DeviceInfo getStatus(DeviceInfo devInfo) throws OneM2MException {
	
	OneM2MDmAdapter adaptor = new OneM2MDmAdapter(CfgManager.getInstance().getOneM2mAgentAddress());
	
	String deviceId = devInfo.getObjectIDs().get(0);
	
	Document nodeDoc = context.getDatabaseManager().getCollection(CfgManager.getInstance().getResourceDatabaseName())
			.find(new BasicDBObject(Naming.NODEID_SN, deviceId)).first();
	String agentAddress = "";
	agentAddress = nodeDoc.getString(Naming.MGMTCLIENTADDRESS);
	if(agentAddress != null && !agentAddress.equals("")) {
		adaptor = new OneM2MDmAdapter(agentAddress);
	}
	
	try {
		
		Document doc = adaptor.readDeviceStatus(deviceId, "deviceinfo");
		devInfo.setFwVersion(doc.getString("fw_version"));
		devInfo.setSwVersion(doc.getString("os_version"));
		devInfo.setDeviceLabel(doc.getString("serial"));
		devInfo.setManufacturer(doc.getString("manufacturer"));
		devInfo.setModel(doc.getString("model"));
		
	} catch (HitDMException e) {
		
		throw convertHitDMExToOneM2MEx(e);
	} catch(IOException ex) {
		ex.printStackTrace();
		return null;
	}
	
	return devInfo;
}
 
Example 5
Source File: OneM2MDmController.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public EventLog getStatus(EventLog evtLog) throws OneM2MException {
	
	OneM2MDmAdapter adaptor = new OneM2MDmAdapter(CfgManager.getInstance().getOneM2mAgentAddress());
	
	String deviceId = evtLog.getObjectIDs().get(0);
	
	Document nodeDoc = context.getDatabaseManager().getCollection(CfgManager.getInstance().getResourceDatabaseName())
			.find(new BasicDBObject(Naming.NODEID_SN, deviceId)).first();
	String agentAddress = "";
	agentAddress = nodeDoc.getString(Naming.MGMTCLIENTADDRESS);
	if(agentAddress != null && !agentAddress.equals("")) {
		adaptor = new OneM2MDmAdapter(agentAddress);
	}
	
	try {
		
		Document doc = adaptor.readDeviceStatus(deviceId, "debug/status");
		evtLog.setLogStatus(doc.getBoolean("status") == true ? 1 : 2);
		
	} catch (HitDMException e) {
		
		throw convertHitDMExToOneM2MEx(e);
	} catch(IOException ex) {
		ex.printStackTrace();
		return null;
	}
	
	return evtLog;
}
 
Example 6
Source File: Developer.java    From repositoryminer with Apache License 2.0 5 votes vote down vote up
/**
 * Converts a document to a developer.
 * 
 * @param document
 * 
 * @return a document.
 */
public static Developer parseDocument(Document document) {
	if (document == null) {
		return null;
	}
	
	Developer c = new Developer(document.getString("name"), document.getString("email"));
	return c;
}
 
Example 7
Source File: OneM2MDmController.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public EventLog getStatus(EventLog evtLog) throws OneM2MException {
	
	OneM2MDmAdapter adaptor = new OneM2MDmAdapter(CfgManager.getInstance().getOneM2mAgentAddress());
	
	String deviceId = evtLog.getObjectIDs().get(0);
	
	Document nodeDoc = context.getDatabaseManager().getCollection(CfgManager.getInstance().getResourceDatabaseName())
			.find(new BasicDBObject(Naming.NODEID_SN, deviceId)).first();
	String agentAddress = "";
	agentAddress = nodeDoc.getString(Naming.MGMTCLIENTADDRESS);
	if(agentAddress != null && !agentAddress.equals("")) {
		adaptor = new OneM2MDmAdapter(agentAddress);
	}
	
	try {
		
		Document doc = adaptor.readDeviceStatus(deviceId, "debug/status");
		evtLog.setLogStatus(doc.getBoolean("status") == true ? 1 : 2);
		
	} catch (HitDMException e) {
		
		throw convertHitDMExToOneM2MEx(e);
	} catch(IOException ex) {
		ex.printStackTrace();
		return null;
	}
	
	return evtLog;
}
 
Example 8
Source File: TodoItem.java    From stitch-android-sdk with Apache License 2.0 5 votes vote down vote up
/** Constructs a todo item from a MongoDB document. */
TodoItem(final Document todoItemDoc) {
  this.id = todoItemDoc.getObjectId(ID_KEY);
  this.task = todoItemDoc.getString(TASK_KEY);
  this.checked = todoItemDoc.getBoolean(CHECKED_KEY);
  if (todoItemDoc.containsKey(DONE_DATE_KEY)) {
    this.doneDate = todoItemDoc.getDate(DONE_DATE_KEY);
  }
}
 
Example 9
Source File: OneM2MDmController.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public DeviceInfo getStatus(DeviceInfo devInfo) throws OneM2MException {
	
	OneM2MDmAdapter adaptor = new OneM2MDmAdapter(CfgManager.getInstance().getOneM2mAgentAddress());
	
	String deviceId = devInfo.getObjectIDs().get(0);
	
	Document nodeDoc = context.getDatabaseManager().getCollection(CfgManager.getInstance().getResourceDatabaseName())
			.find(new BasicDBObject(Naming.NODEID_SN, deviceId)).first();
	String agentAddress = "";
	agentAddress = nodeDoc.getString(Naming.MGMTCLIENTADDRESS);
	if(agentAddress != null && !agentAddress.equals("")) {
		adaptor = new OneM2MDmAdapter(agentAddress);
	}
	
	try {
		
		Document doc = adaptor.readDeviceStatus(deviceId, "deviceinfo");
		devInfo.setFwVersion(doc.getString("fw_version"));
		devInfo.setSwVersion(doc.getString("os_version"));
		devInfo.setDeviceLabel(doc.getString("serial"));
		devInfo.setManufacturer(doc.getString("manufacturer"));
		devInfo.setModel(doc.getString("model"));
		
	} catch (HitDMException e) {
		
		throw convertHitDMExToOneM2MEx(e);
	} catch(IOException ex) {
		ex.printStackTrace();
		return null;
	}
	
	return devInfo;
}
 
Example 10
Source File: MongoHealthCheckRequester.java    From hesperides with GNU General Public License v3.0 5 votes vote down vote up
static MongoHealthCheckResult performHealthCheck(MongoTemplate mongoTemplate) {
    Instant start = Instant.now();
    Document result = mongoTemplate.executeCommand("{ buildInfo: 1 }");
    Instant end = Instant.now();
    Duration duration = Duration.between(start, end);
    return new MongoHealthCheckResult(
            result.getString("version"),
            duration.getSeconds() * 1000 + duration.getNano() / 1000000.0);
}
 
Example 11
Source File: ResourceDAO.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public Resource getResource(String id) throws OneM2MException {

		Document doc = this.getDocument(id);
		if (doc == null) {
			return null;
		}

		log.debug(doc.toJson());
		
		RESOURCE_TYPE resType = RESOURCE_TYPE.get((int) doc.get(RESTYPE_KEY));
		String contDefinition = doc.getString(CONTAINER_DEFINITION_KEY);		// added in 2016-11-21
		//DaoJSONConvertor<?> jc = getJsonConvertor(resType);  blocked in 2016-11-21
		DaoJSONConvertor<?> jc = null;
		
		if(contDefinition != null && !contDefinition.equals("")) {
			jc = getFlexContainerJsonConvertor(contDefinition);
		} else {
			jc = getJsonConvertor(resType);
		}
		
		Resource res;
		try {
			res = (Resource) jc.unmarshal(doc.toJson());
			res.setUri(doc.getString(URI_KEY));
			// res.setId(doc.getString(OID_KEY));
		} catch (Exception e) {
			log.debug("Handled exception", e);
			throw new OneM2MException(RESPONSE_STATUS.INTERNAL_SERVER_ERROR,
					"unmarshal file in ResouceDAO.getResourceWithUri:"
							+ doc.toJson());
		}
		return res;
	}
 
Example 12
Source File: ResourceDAO.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
protected void create(Resource res) throws OneM2MException {
	
	Document curDoc = getDocument(URI_KEY, res.getUri());
	if (curDoc != null) {
		// added to support logic to delete expired resource
		// logic added in 2016-12-27
		String expirationTime = curDoc.getString(EXPIRETIME_KEY);
		if(expirationTime != null && Utils.checkIfExpired(expirationTime)) {
			String resUri = curDoc.getString(URI_KEY);
			this.deleteDocument(URI_KEY, resUri);
		} else {
			throw new OneM2MException(RESPONSE_STATUS.CONFLICT,
					"Resource already exist!!! :" + res.getUri());
		}
	}		

	String strJson = resourceToJson(res);
	log.debug("Res json: {} ", strJson);
	
	String currentTime = getTimeString(LocalDateTime.now());
	res.setCreationTime(currentTime);
	res.setLastModifiedTime(currentTime);

	Document doc = Document.parse(strJson);
	doc.append(ResourceDAO.URI_KEY, res.getUri());
	doc.append(ResourceDAO.CRETIME_KEY, currentTime);
	doc.append(ResourceDAO.LASTMODTIME_KEY, currentTime);

	MongoCollection<Document> collection = context.getDatabaseManager()
			.getCollection(collectionName);

	collection.insertOne(doc);
	
}
 
Example 13
Source File: ResourceDAO.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
protected void create(Resource res) throws OneM2MException {
	
	Document curDoc = getDocument(URI_KEY, res.getUri());
	if (curDoc != null) {
		// added to support logic to delete expired resource
		// logic added in 2016-12-27
		String expirationTime = curDoc.getString(EXPIRETIME_KEY);
		if(expirationTime != null && Utils.checkIfExpired(expirationTime)) {
			String resUri = curDoc.getString(URI_KEY);
			this.deleteDocument(URI_KEY, resUri);
		} else {
			throw new OneM2MException(RESPONSE_STATUS.CONFLICT,
					"Resource already exist!!! :" + res.getUri());
		}
	}		

	String strJson = resourceToJson(res);
	log.debug("Res json: {} ", strJson);
	
	String currentTime = getTimeString(LocalDateTime.now());
	res.setCreationTime(currentTime);
	res.setLastModifiedTime(currentTime);

	Document doc = Document.parse(strJson);
	doc.append(ResourceDAO.URI_KEY, res.getUri());
	doc.append(ResourceDAO.CRETIME_KEY, currentTime);
	doc.append(ResourceDAO.LASTMODTIME_KEY, currentTime);

	MongoCollection<Document> collection = context.getDatabaseManager()
			.getCollection(collectionName);

	collection.insertOne(doc);
	
}
 
Example 14
Source File: MongoAuthenticationProvider.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
private User createUser(Document document) {
    String username = document.getString(FIELD_USERNAME);
    DefaultUser user = new DefaultUser(username);
    Map<String, Object> claims = new HashMap<>();

    String sub = document.containsKey(FIELD_ID) ?
            document.get(FIELD_ID) instanceof ObjectId ? ((ObjectId) document.get(FIELD_ID)).toString() : document.getString(FIELD_ID)
            : username;
    // set technical id
    user.setId(sub);

    // set user roles
    user.setRoles(getUserRoles(document));

    // set claims
    claims.put(StandardClaims.SUB, sub);
    claims.put(StandardClaims.PREFERRED_USERNAME, username);
    if (this.mapper.getMappers() != null && !this.mapper.getMappers().isEmpty()) {
        this.mapper.getMappers().forEach((k, v) -> claims.put(k, document.get(v)));
    } else {
        // default claims
        // remove reserved claims
        document.remove(FIELD_ID);
        document.remove(FIELD_USERNAME);
        document.remove(configuration.getPasswordField());
        document.remove(FIELD_CREATED_AT);
        if (document.containsKey(FIELD_UPDATED_AT)) {
            document.put(StandardClaims.UPDATED_AT, document.get(FIELD_UPDATED_AT));
            document.remove(FIELD_UPDATED_AT);
        }
        document.entrySet().forEach(entry -> claims.put(entry.getKey(), entry.getValue()));
    }
    user.setAdditionalInformation(claims);

    return user;
}
 
Example 15
Source File: ScoredPattern.java    From baleen with Apache License 2.0 5 votes vote down vote up
/**
 * Construct the Scored pattern from the given document
 *
 * @param document (mongo) to construct from
 */
public ScoredPattern(Document document) {

  pattern = document.getString(PATTERN_FACT_FIELD);
  frequency = document.getInteger(FREQUENCY_KEY);
  coherence = document.getDouble(COHERENCE_KEY);
}
 
Example 16
Source File: StitchEvent.java    From stitch-android-sdk with Apache License 2.0 4 votes vote down vote up
private StitchEvent(final String eventName,
                    final String data,
                    final Decoder<T> decoder) {
  this.eventName = eventName;
  if (data == null) {
    this.data = null;
    this.error = null;
    return;
  }

  final StringBuilder decodedStringBuilder = new StringBuilder(data.length());
  for (int chIdx = 0; chIdx < data.length(); chIdx++) {
    final char c = data.charAt(chIdx);
    switch (c) {
      case '%':
        if (chIdx + 2 >= data.length()) {
          break;
        }
        final String code = data.substring(chIdx + 1, chIdx + 3);
        final boolean found;
        switch (code) {
          case "25":
            found = true;
            decodedStringBuilder.append("%");
            break;
          case "0A":
            found = true;
            decodedStringBuilder.append("\n");
            break;
          case "0D":
            found = true;
            decodedStringBuilder.append("\r");
            break;
          default:
            found = false;
        }
        if (found) {
          chIdx += 2;
          continue;
        }
        break;
      default:
        break;
    }
    decodedStringBuilder.append(c);
  }
  final String decodedData = decodedStringBuilder.toString();

  switch (this.eventName) {
    case ERROR_EVENT_NAME:
      String errorMsg;
      StitchServiceErrorCode errorCode;

      try {
        // parse the error as json
        // if it is not valid json, parse the body as seen in
        // StitchError#handleRequestError
        final Document errorDoc =
            BsonUtils.parseValue(decodedData, Document.class);
        errorMsg = errorDoc.getString(ErrorFields.ERROR);
        errorCode = StitchServiceErrorCode.fromCodeName(
            errorDoc.getString(ErrorFields.ERROR_CODE));
      } catch (Exception e) {
        errorMsg = decodedData;
        errorCode = StitchServiceErrorCode.UNKNOWN;
      }
      this.error = new StitchServiceException(errorMsg, errorCode);
      this.data = null;
      break;
    case Event.MESSAGE_EVENT:
      this.data = BsonUtils.parseValue(decodedData, decoder);
      this.error = null;
      break;
    default:
      this.data = null;
      this.error = null;
      break;
  }
}
 
Example 17
Source File: ComputeTestFailingStats.java    From repairnator with MIT License 4 votes vote down vote up
public static void main(String[] args) throws IOException {

        if (args.length < 4) {
            System.err.println("Usage: java ComputeTestFailingStats <url of mongodb with auth> <db name> <collection name> <path of the file to write>");
            System.exit(-1);
        }

        Map<String, Integer> occurencesByFailure = new HashMap<>();
        String dbCollectionUrl = args[0];
        String dbName = args[1];
        String collectionName = args[2];

        String pathOutput = args[3];
        File outputFile = new File(pathOutput);

        MongoConnection mongoConnection = new MongoConnection(dbCollectionUrl, dbName);
        MongoDatabase database = mongoConnection.getMongoDatabase();
        MongoCollection<Document> collection = database.getCollection(collectionName);

        Calendar limitDateFebruary2017 = Calendar.getInstance();
        Calendar limitDateJanuary2018 = Calendar.getInstance();
        limitDateFebruary2017.set(2017, Calendar.FEBRUARY, 1);
        limitDateJanuary2018.set(2018, Calendar.JANUARY, 1);

        Block<Document> block = new Block<Document>(){

            @Override
            public void apply(Document document) {
                totalFailingBuild++;
                String typeOfFailures = document.getString("typeOfFailures");

                for (String failure : typeOfFailures.split(",")) {
                    if (failure.endsWith(":")) {
                        failure = failure.substring(0, failure.length()-1);
                    }
                    if (failure.equals("skip") || failure.equals("skipped")) {
                        continue;
                    }
                    if (!occurencesByFailure.containsKey(failure)) {
                        occurencesByFailure.put(failure, 0);
                    }
                    int nbOcc = occurencesByFailure.get(failure);
                    nbOcc++;
                    occurencesByFailure.put(failure, nbOcc);
                    totalNumberOfFailures++;
                }
            }
        };
        collection.find(
                and(
                        lt("buildFinishedDate", limitDateJanuary2018.getTime()),
                        gt("buildFinishedDate", limitDateFebruary2017.getTime()),
                        in("status", "PATCHED", "test errors", "test failure")
                )
        ).forEach(
                block
        );

        BufferedWriter buffer = new BufferedWriter(new FileWriter(outputFile));
        buffer.write("failure\tNb Occurences\n");
        buffer.flush();



        for (Map.Entry<String,Integer> entry : occurencesByFailure.entrySet().stream().sorted(Map.Entry.comparingByValue(Collections.reverseOrder())).collect(Collectors.toList())) {
            buffer.write(entry.getKey()+"\t"+entry.getValue()+"\n");
            buffer.flush();
        }

        buffer.close();
        System.out.println("Output written to "+pathOutput+" - "+totalFailingBuild+" failing build detected and "+totalNumberOfFailures+" failures counted.");
    }
 
Example 18
Source File: MongoCompensableLogger.java    From ByteTCC with GNU Lesser General Public License v3.0 4 votes vote down vote up
private List<XAResourceArchive> constructParticipantList(Document document) {
	XidFactory compensableXidFactory = this.beanFactory.getCompensableXidFactory();

	List<XAResourceArchive> resourceList = new ArrayList<XAResourceArchive>();
	Document participants = document.get("participants", Document.class);
	for (Iterator<String> itr = participants.keySet().iterator(); itr.hasNext();) {
		String key = itr.next();
		Document element = participants.get(key, Document.class);

		XAResourceArchive participant = new XAResourceArchive();

		String gxid = element.getString(CONSTANTS_FD_GLOBAL);
		String bxid = element.getString(CONSTANTS_FD_BRANCH);

		String descriptorType = element.getString("type");
		String identifier = element.getString("resource");

		int vote = element.getInteger("vote");
		boolean committed = element.getBoolean("committed");
		boolean rolledback = element.getBoolean("rolledback");
		boolean readonly = element.getBoolean("readonly");
		boolean completed = element.getBoolean("completed");
		boolean heuristic = element.getBoolean("heuristic");

		byte[] globalTransactionId = ByteUtils.stringToByteArray(gxid);
		byte[] branchQualifier = ByteUtils.stringToByteArray(bxid);
		TransactionXid globalId = compensableXidFactory.createGlobalXid(globalTransactionId);
		TransactionXid branchId = compensableXidFactory.createBranchXid(globalId, branchQualifier);
		participant.setXid(branchId);

		XAResourceDeserializer resourceDeserializer = this.beanFactory.getResourceDeserializer();
		XAResourceDescriptor descriptor = resourceDeserializer.deserialize(identifier);
		if (descriptor != null //
				&& descriptor.getClass().getName().equals(descriptorType) == false) {
			throw new IllegalStateException();
		}

		participant.setVote(vote);
		participant.setCommitted(committed);
		participant.setRolledback(rolledback);
		participant.setReadonly(readonly);
		participant.setCompleted(completed);
		participant.setHeuristic(heuristic);

		participant.setDescriptor(descriptor);

		resourceList.add(participant);
	}

	return resourceList;
}
 
Example 19
Source File: MarketDataServiceBasicImpl.java    From redtorch with MIT License 4 votes vote down vote up
public List<TickField> documentListToTickList(List<Document> documentList, String gatewayId) {
	List<TickField> tickList = new ArrayList<>();
	if (documentList != null && !documentList.isEmpty()) {
		long beginTime = System.currentTimeMillis();
		for (Document document : documentList) {
			try {
				TickField.Builder tickBuilder = TickField.newBuilder();
				ContractField.Builder contractBuilder = ContractField.newBuilder();

				String unifiedSymbol = document.getString("unifiedSymbol");
				String[] unifiedSymbolStrArr = unifiedSymbol.split("@");
				String symbol = unifiedSymbolStrArr[0];
				String exchangeStr = unifiedSymbolStrArr[1];
				String productClassStr = unifiedSymbolStrArr[2];

				contractBuilder.setUnifiedSymbol(unifiedSymbol);
				contractBuilder.setSymbol(symbol);
				contractBuilder.setExchange(ExchangeEnum.valueOf(exchangeStr));
				contractBuilder.setProductClass(ProductClassEnum.valueOf(productClassStr));

				tickBuilder.setUnifiedSymbol(unifiedSymbol);
				tickBuilder.setGatewayId(gatewayId);

				List<Double> askPriceList = new ArrayList<>();
				List<Integer> askVolumeList = new ArrayList<>();
				for (int i = 0; i < 5; i++) {
					askPriceList.add(document.getDouble("askPrice" + (i + 1)));
					askVolumeList.add(document.getInteger("askVolume" + (i + 1)));
				}
				tickBuilder.addAllAskPrice(askPriceList);
				tickBuilder.addAllAskVolume(askVolumeList);

				tickBuilder.setActionDay(document.getString("actionDay"));
				tickBuilder.setActionTime(document.getString("actionTime"));
				tickBuilder.setActionTimestamp(document.getLong("actionTimestamp"));
				tickBuilder.setAvgPrice(document.getDouble("avgPrice"));

				List<Double> bidPriceList = new ArrayList<>();
				List<Integer> bidVolumeList = new ArrayList<>();
				for (int i = 0; i < 5; i++) {
					bidPriceList.add(document.getDouble("bidPrice" + (i + 1)));
					bidVolumeList.add(document.getInteger("bidVolume" + (i + 1)));
				}
				tickBuilder.addAllBidPrice(bidPriceList);
				tickBuilder.addAllBidVolume(bidVolumeList);

				tickBuilder.setLastPrice(document.getDouble("lastPrice"));
				tickBuilder.setHighPrice(document.getDouble("highPrice"));
				tickBuilder.setIopv(document.getDouble("iopv"));
				tickBuilder.setLowPrice(document.getDouble("lowPrice"));
				tickBuilder.setLowerLimit(document.getDouble("lowerLimit"));
				tickBuilder.setNumTrades(document.getLong("numTrades"));
				tickBuilder.setNumTradesDelta(document.getLong("numTradesDelta"));
				tickBuilder.setOpenInterest(document.getDouble("openInterest"));
				tickBuilder.setOpenInterestDelta(document.getDouble("openInterestDelta"));
				tickBuilder.setOpenPrice(document.getDouble("openPrice"));
				tickBuilder.setPreClosePrice(document.getDouble("preClosePrice"));
				tickBuilder.setPreOpenInterest(document.getDouble("preOpenInterest"));
				tickBuilder.setPreSettlePrice(document.getDouble("preSettlePrice"));
				tickBuilder.setSettlePrice(document.getDouble("settlePrice"));
				tickBuilder.setStatus(document.getInteger("status"));
				tickBuilder.setTotalAskVol(document.getLong("totalAskVol"));
				tickBuilder.setTotalBidVol(document.getLong("totalBidVol"));
				tickBuilder.setTradingDay(document.getString("tradingDay"));
				tickBuilder.setTurnover(document.getDouble("turnover"));
				tickBuilder.setTurnoverDelta(document.getDouble("turnoverDelta"));
				tickBuilder.setUpperLimit(document.getDouble("upperLimit"));
				tickBuilder.setVolume(document.getLong("volume"));
				tickBuilder.setVolumeDelta(document.getLong("volumeDelta"));
				tickBuilder.setWeightedAvgAskPrice(document.getDouble("weightedAvgAskPrice"));
				tickBuilder.setWeightedAvgBidPrice(document.getDouble("weightedAvgBidPrice"));
				tickBuilder.setYieldToMaturity(document.getDouble("yieldToMaturity"));

				tickList.add(tickBuilder.build());
			} catch (Exception e) {
				logger.error("数据转换错误", e);
			}
		}
		logger.info("MongoDB文档集合转为Tick对象集合耗时{}ms,共{}条数据", (System.currentTimeMillis() - beginTime), tickList.size());
	} else {
		logger.warn("MongoDB文档集合转为Tick对象集合时传入的文档集合为空");
	}

	return tickList;
}
 
Example 20
Source File: Person.java    From microshed-testing with Apache License 2.0 4 votes vote down vote up
public static Person fromDocument(Document doc) {
    return new Person(doc.getString("name"), doc.getInteger("age"), doc.getLong("id"));
}