Java Code Examples for com.google.gson.JsonArray#size()

The following examples show how to use com.google.gson.JsonArray#size() . 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: RestApi.java    From syncthing-android with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Retrieves the events that have accumulated since the given event id.
 *
 * The OnReceiveEventListeners onEvent method is called for each event.
 */
public final void getEvents(final long sinceId, final long limit, final OnReceiveEventListener listener) {
    Map<String, String> params =
            ImmutableMap.of("since", String.valueOf(sinceId), "limit", String.valueOf(limit));
    new GetRequest(mContext, mUrl, GetRequest.URI_EVENTS, mApiKey, params, result -> {
        JsonArray jsonEvents = new JsonParser().parse(result).getAsJsonArray();
        long lastId = 0;

        for (int i = 0; i < jsonEvents.size(); i++) {
            JsonElement json = jsonEvents.get(i);
            Event event = new Gson().fromJson(json, Event.class);

            if (lastId < event.id)
                lastId = event.id;

            listener.onEvent(event);
        }

        listener.onDone(lastId);
    });
}
 
Example 2
Source File: MCRWCMSFileBrowserResource.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
protected JsonObject getFolder(File node, boolean folderallowed) {
    JsonObject jsonObj = new JsonObject();
    jsonObj.addProperty("name", node.getName());
    jsonObj.addProperty("path", node.getAbsolutePath());
    jsonObj.addProperty("allowed", folderallowed);
    if (node.isDirectory()) {
        jsonObj.addProperty("type", "folder");
        JsonArray jsonArray = new JsonArray();
        File[] childNodes = node.listFiles();
        for (File child : childNodes) {
            if (child.isDirectory()) {
                if (folderallowed || folderList.contains(child.getPath())) {
                    jsonArray.add(getFolder(child, true));
                } else {
                    jsonArray.add(getFolder(child, false));
                }
            }
        }
        if (jsonArray.size() > 0) {
            jsonObj.add("children", jsonArray);
        }
        return jsonObj;
    }
    return jsonObj;
}
 
Example 3
Source File: WxMaCodeVersionDistributionGsonAdapter.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
private Map<String, Float> getAsMap(JsonObject object, String memberName) {
  JsonArray array = object.getAsJsonArray(memberName);
  if (array != null && array.size() > 0) {
    Map<String, Float> map = new LinkedHashMap<>(array.size());
    for (JsonElement element : array) {
      JsonObject elementObject = element.getAsJsonObject();
      String version = GsonHelper.getString(elementObject, "version");
      if (version != null) {
        Float percentage = GsonHelper.getFloat(elementObject, "percentage");
        map.put(version, percentage);
      }
    }
    return map;
  }
  return null;
}
 
Example 4
Source File: OracleMobileDeviceManagement.java    From product-emm with Apache License 2.0 6 votes vote down vote up
@Test(dependsOnMethods = {"addEnrollment"}, description = "Test view device types")
public void testViewDeviceTypes() throws Exception {
    MDMResponse response = client.get(Constants.MobileDeviceManagement.VIEW_DEVICE_TYPES_ENDPOINT);
    Assert.assertEquals(HttpStatus.SC_OK, response.getStatus());
    //Assert.assertEquals(PayloadGenerator.getJsonPayloadToString
      //      (Constants.MobileDeviceManagement.VIEW_DEVICE_RESPONSE_PAYLOAD_FILE_NAME),response.getBody());
    JsonArray responseDeviceTypes = parser.parse(response.getBody()).getAsJsonArray();
    Set<String> deviceTypesSet = new HashSet<>();
    for (int i = 0; i < responseDeviceTypes.size(); i++) {
        deviceTypesSet.add(responseDeviceTypes.get(i).getAsJsonObject().get("name").getAsString());
    }
    JsonArray deviceTypes = PayloadGenerator.getJsonPayload(
            Constants.MobileDeviceManagement.VIEW_DEVICE_RESPONSE_PAYLOAD_FILE_NAME);
    for (int i = 0; i < deviceTypes.size(); i++) {
        String type = deviceTypes.get(i).getAsJsonObject().get("name").getAsString();
        Assert.assertTrue(deviceTypesSet.contains(type));

    }
    //Response has two device types, because in windows enrollment a windows device is previously enrolled.
}
 
Example 5
Source File: ServerDtoTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testSerializerWithAny() throws Exception {
  final List<Object> objects = createListTestValueForAny();
  DtoWithAny dto =
      dtoFactory
          .createDto(DtoWithAny.class)
          .withStuff(createTestValueForAny())
          .withObjects(objects);
  final String json = dtoFactory.toJson(dto);

  JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();
  Assert.assertEquals(jsonObject.get("stuff"), createTestValueForAny());

  Assert.assertTrue(jsonObject.has("objects"));
  JsonArray jsonArray = jsonObject.get("objects").getAsJsonArray();
  assertEquals(jsonArray.size(), objects.size());
  for (int i = 0; i < jsonArray.size(); i++) {
    assertEquals(jsonArray.get(i), objects.get(i));
  }
}
 
Example 6
Source File: DuplicateRepoWorker.java    From compiler with Apache License 2.0 6 votes vote down vote up
private void removeDuplicates(){
	System.out.println(Thread.currentThread().getId() + " Responsible for processing: " + from + " and " + to);
	File[] files = new File(inPath).listFiles(); 
	for (int i = from; i < to; i++){
		File repoFile = files[i];
		String content = FileIO.readFileContents(repoFile);
		Gson parser = new Gson();
		JsonArray repos = parser.fromJson(content, JsonElement.class).getAsJsonArray();
		int size = repos.size();
		for (int j = 0; j < size; j++) {
			JsonObject repo = repos.get(j).getAsJsonObject();
			String name = repo.get("full_name").getAsString();
			if (names.contains(name)) {
				System.out.println("found a duplicate " + name);
				continue;
			}
			names.add(name);
			this.addRepo(repo);
		}
		System.out.println(Thread.currentThread().getId() + " processing: " + i);
	}
	this.writeRemainingRepos();
	System.out.print(Thread.currentThread().getId() + "finished");
}
 
Example 7
Source File: ScryFallProvider.java    From MtgDesktopCompanion with GNU General Public License v3.0 6 votes vote down vote up
private void generateRules(MagicCard mc) throws IOException {
	
	if(getBoolean("LOAD_RULING"))
	{
		String url = getString("URL")+CARDS + mc.getId() + "/rulings";
	
		JsonElement el = URLTools.extractJson(url);
		JsonArray arr = el.getAsJsonObject().get("data").getAsJsonArray();

		for (int i = 0; i < arr.size(); i++) {
			JsonObject obr = arr.get(i).getAsJsonObject();
			MagicRuling rul = new MagicRuling();
			rul.setDate(obr.get("published_at").getAsString());
			rul.setText(obr.get("comment").getAsString());

			mc.getRulings().add(rul);
		}
	}
}
 
Example 8
Source File: BaseWxMpServiceImpl.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Override
public String[] getCallbackIP() throws WxErrorException {
  String responseContent = this.get(WxMpService.GET_CALLBACK_IP_URL, null);
  JsonElement tmpJsonElement = JSON_PARSER.parse(responseContent);
  JsonArray ipList = tmpJsonElement.getAsJsonObject().get("ip_list").getAsJsonArray();
  String[] ipArray = new String[ipList.size()];
  for (int i = 0; i < ipList.size(); i++) {
    ipArray[i] = ipList.get(i).getAsString();
  }
  return ipArray;
}
 
Example 9
Source File: KcaDeckInfo.java    From kcanotify with GNU General Public License v3.0 5 votes vote down vote up
public void debugPortInfo(JsonArray deckPortData, int deckid) {
    JsonArray deckShipIdList = (JsonArray) ((JsonObject) deckPortData.get(deckid)).get("api_ship");
    for (int i = 0; i < deckShipIdList.size(); i++) {
        int shipId = deckShipIdList.get(i).getAsInt();
        if (shipId != -1) {
            JsonObject shipData = getUserShipDataById(shipId, "ship_id,lv,slot,onslot");
            int shipKcId = shipData.get("ship_id").getAsInt();
            int shipLv = shipData.get("lv").getAsInt();
            JsonObject shipKcData = getKcShipDataById(shipKcId, "name");
            String shipName = shipKcData.get("name").getAsString();
            Log.e("KCA", KcaUtils.format("%s (%s)", shipName, shipLv));
            JsonArray shipItem = (JsonArray) shipData.get("slot");
            JsonArray shipSlotCount = (JsonArray) shipData.get("onslot");
            for (int j = 0; j < shipItem.size(); j++) {
                int item_id = shipItem.get(j).getAsInt();
                int slot = shipSlotCount.get(j).getAsInt();
                if (item_id != -1) {
                    JsonObject itemData = getUserItemStatusById(item_id, "level,alv", "name,type,tyku");
                    if (itemData == null) continue;
                    String itemName = itemData.get("name").getAsString();
                    int itemLevel = itemData.get("level").getAsInt();
                    int itemMastery = 0;
                    if (itemData.has("alv")) {
                        itemMastery = itemData.get("alv").getAsInt();
                    }
                    int itemType = itemData.get("type").getAsJsonArray().get(2).getAsInt();
                    Log.e("KCA", KcaUtils.format("- %s %d %d %d", itemName, itemLevel, itemMastery, slot));
                }
            }
        }
    }
}
 
Example 10
Source File: HierarchyDetailsService.java    From Insights with Apache License 2.0 5 votes vote down vote up
private void createJsonObject(Node node, JsonObject parentJson) {
	JsonArray childArray = new JsonArray();
	// recurse
	for (Node childNode : node.getChildren()) {
		JsonObject childJson = new JsonObject();
		childJson.addProperty(DatataggingConstants.NAME, childNode.getName());
		childArray.add(childJson);
		createJsonObject(childNode, childJson);
	}
	if (childArray.size() != 0) {
		parentJson.add(DatataggingConstants.CHILDREN, childArray);
	}
}
 
Example 11
Source File: ExtractWidgetFeedback.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static List<ExtractWidgetFeedback> fromJsonArray(JsonArray jsonArray) {
  if (jsonArray == null) {
    return EMPTY_LIST;
  }
  ArrayList<ExtractWidgetFeedback> list = new ArrayList<ExtractWidgetFeedback>(jsonArray.size());
  Iterator<JsonElement> iterator = jsonArray.iterator();
  while (iterator.hasNext()) {
    list.add(fromJson(iterator.next().getAsJsonObject()));
  }
  return list;
}
 
Example 12
Source File: DataElementOperandParser.java    From dhis2-android-datacapture with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static List<DataElementOperand> parseToDataElementOperandsList(String responseBody)
        throws ParsingException {
    if (responseBody != null) {
        List<DataElementOperand> dataElementOperandList = new ArrayList<>();
        JsonObject jsonForm = JsonHandler.buildJsonObject(responseBody);
        JsonArray jsonArray = jsonForm.getAsJsonArray("compulsoryDataElementOperands");
        if (jsonArray.size() == 0) {
            return dataElementOperandList;
        }
        parseToDataElementOperandsList(dataElementOperandList, jsonArray);
        return dataElementOperandList;
    }
    return null;
}
 
Example 13
Source File: KcaApiData.java    From kcanotify with GNU General Public License v3.0 5 votes vote down vote up
public static int updatePortDataOnBattle(JsonObject api_data) {
    if (api_data.has("api_ship_data")) {
        JsonArray shipDataArray = (JsonArray) api_data.get("api_ship_data");
        JsonElement temp;
        for (Iterator<JsonElement> itr = shipDataArray.iterator(); itr.hasNext(); ) {
            temp = itr.next();
            Integer api_id = temp.getAsJsonObject().get("api_id").getAsInt();
            userShipData.put(api_id, temp.getAsJsonObject());
        }
        return shipDataArray.size();
    } else {
        return -1;
    }
}
 
Example 14
Source File: EventDeserializer.java    From easypost-java with MIT License 5 votes vote down vote up
private Object[] deserializeJsonArray(JsonArray arr) {
	Object[] elems = new Object[arr.size()];
	Iterator<JsonElement> elemIter = arr.iterator();
	int i = 0;
	while (elemIter.hasNext()) {
		JsonElement elem = elemIter.next();
		elems[i++] = deserializeJsonElement(elem);
	}
	return elems;
}
 
Example 15
Source File: TextMessageEventFactory.java    From messenger4j with MIT License 5 votes vote down vote up
private Map<String, Set<NLPEntity>> getNlpEntitiesFromJsonObject(JsonObject jsonObject) {
  final Map<String, Set<NLPEntity>> nlpEntities = new HashMap<>();
  for (String key : jsonObject.keySet()) {
    final JsonArray valuesJsonArray = jsonObject.getAsJsonArray(key);
    final Set<NLPEntity> values = new HashSet<>(valuesJsonArray.size());
    for (JsonElement jsonElement : valuesJsonArray) {
      values.add(new NLPEntity(jsonElement.toString()));
    }
    nlpEntities.put(key, Collections.unmodifiableSet(values));
  }
  return nlpEntities;
}
 
Example 16
Source File: ObjectType.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
private Object coerceCollection(String fieldName, JsonArray jsonArray, AttributeType fieldType) {
   Collection<Object> collection;
   AttributeType containedType;
   if(fieldType instanceof SetType) {
      if(jsonArray.size() == 0) {
         return new HashSet<Object>();
      }
      collection = new HashSet<Object>(jsonArray.size());
      containedType = ((SetType) fieldType).getContainedType();
   }
   else if(fieldType instanceof ListType || fieldType instanceof AnyType) {
      if(jsonArray.size() == 0) {
         return new ArrayList<Object>();
      }
      collection = new ArrayList<Object>(jsonArray.size());
      containedType = (fieldType instanceof AnyType) ? AnyType.INSTANCE : ((ListType) fieldType).getContainedType();
   }
   else {
      // TODO just drop it?
      throw new IllegalArgumentException("Cannot coerce field " + fieldName + " to " + fieldType.getTypeName());
   }
   
   int index = 0;
   for(JsonElement e: jsonArray) {
      collection.add(coerceElement(fieldName + "[" + index + "]", e, containedType));
   }
   return collection;
}
 
Example 17
Source File: SceneDiscovery.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
private HashMap<Integer, List<Short>> getReachableGroups(ConnectionManager connectionManager) {
    HashMap<Integer, List<Short>> reachableGroupsMap = null;
    String response = connectionManager.getHttpTransport()
            .execute(SceneDiscovery.REACHABLE_GROUPS_QUERY + connectionManager.getSessionToken());
    if (response == null) {
        return null;
    } else {
        JsonObject responsJsonObj = JSONResponseHandler.toJsonObject(response);
        if (JSONResponseHandler.checkResponse(responsJsonObj)) {
            JsonObject resultJsonObj = JSONResponseHandler.getResultJsonObject(responsJsonObj);
            if (resultJsonObj.get(JSONApiResponseKeysEnum.ZONES.getKey()) instanceof JsonArray) {
                JsonArray zones = (JsonArray) resultJsonObj.get(JSONApiResponseKeysEnum.ZONES.getKey());
                reachableGroupsMap = new HashMap<Integer, List<Short>>(zones.size());
                List<Short> groupList;
                for (int i = 0; i < zones.size(); i++) {
                    if (((JsonObject) zones.get(i))
                            .get(JSONApiResponseKeysEnum.GROUPS.getKey()) instanceof JsonArray) {
                        JsonArray groups = (JsonArray) ((JsonObject) zones.get(i))
                                .get(JSONApiResponseKeysEnum.GROUPS.getKey());
                        groupList = new LinkedList<Short>();
                        for (int k = 0; k < groups.size(); k++) {
                            groupList.add(groups.get(k).getAsShort());
                        }
                        reachableGroupsMap.put(((JsonObject) zones.get(i)).get("zoneID").getAsInt(), groupList);
                    }
                }
            }
        }
    }
    return reachableGroupsMap;
}
 
Example 18
Source File: KeycloakUserService.java    From camunda-bpm-identity-keycloak with Apache License 2.0 4 votes vote down vote up
/**
 * Requests users.
 * @param query the user query - not including a groupId criteria
 * @return list of matching users
 */
public List<User> requestUsersWithoutGroupId(KeycloakUserQuery query) {
	List<User> userList = new ArrayList<>();

	StringBuilder resultLogger = new StringBuilder();
	if (KeycloakPluginLogger.INSTANCE.isDebugEnabled()) {
		resultLogger.append("Keycloak user query results: [");
	}

	try {
		// get members of this group
		ResponseEntity<String> response = null;

		if (!StringUtils.isEmpty(query.getId())) {
			response = requestUserById(query.getId());
		} else {
			// Create user search filter
			String userFilter = createUserSearchFilter(query);
			response = restTemplate.exchange(keycloakConfiguration.getKeycloakAdminUrl() + "/users" + userFilter, HttpMethod.GET,
					keycloakContextProvider.createApiRequestEntity(), String.class);
		}
		if (!response.getStatusCode().equals(HttpStatus.OK)) {
			throw new IdentityProviderException(
					"Unable to read users from " + keycloakConfiguration.getKeycloakAdminUrl()
							+ ": HTTP status code " + response.getStatusCodeValue());
		}

		JsonArray searchResult = parseAsJsonArray(response.getBody());
		for (int i = 0; i < searchResult.size(); i++) {
			JsonObject keycloakUser = getJsonObjectAtIndex(searchResult, i);
			if (keycloakConfiguration.isUseEmailAsCamundaUserId() && 
					StringUtils.isEmpty(getJsonString(keycloakUser, "email"))) {
				continue;
			}
			if (keycloakConfiguration.isUseUsernameAsCamundaUserId() &&
					StringUtils.isEmpty(getJsonString(keycloakUser, "username"))) {
				continue;
			}

			UserEntity user = transformUser(keycloakUser);

			// client side check of further query filters
			// beware: looks like most attributes are treated as 'like' queries on Keycloak
			//         and must therefore be seen as a sort of pre-filter only
			if (!matches(query.getId(), user.getId())) continue;
			if (!matches(query.getEmail(), user.getEmail())) continue;
			if (!matches(query.getFirstName(), user.getFirstName())) continue;
			if (!matches(query.getLastName(), user.getLastName())) continue;
			if (!matches(query.getIds(), user.getId())) continue;
			if (!matchesLike(query.getEmailLike(), user.getEmail())) continue;
			if (!matchesLike(query.getFirstNameLike(), user.getFirstName())) continue;
			if (!matchesLike(query.getLastNameLike(), user.getLastName())) continue;
			
			if(isAuthenticatedUser(user) || isAuthorized(READ, USER, user.getId())) {
				userList.add(user);

				if (KeycloakPluginLogger.INSTANCE.isDebugEnabled()) {
					resultLogger.append(user);
					resultLogger.append(" based on ");
					resultLogger.append(keycloakUser.toString());
					resultLogger.append(", ");
				}
			}
		}

	} catch (RestClientException rce) {
		throw new IdentityProviderException("Unable to query users", rce);
	} catch (JsonException je) {
		throw new IdentityProviderException("Unable to query users", je);
	}

	if (KeycloakPluginLogger.INSTANCE.isDebugEnabled()) {
		resultLogger.append("]");
		KeycloakPluginLogger.INSTANCE.userQueryResult(resultLogger.toString());
	}

	// sort users according to query criteria
	if (query.getOrderingProperties().size() > 0) {
		userList.sort(new UserComparator(query.getOrderingProperties()));
	}
	
	// paging
	if ((query.getFirstResult() > 0) || (query.getMaxResults() < Integer.MAX_VALUE)) {
		userList = userList.subList(query.getFirstResult(), 
				Math.min(userList.size(), query.getFirstResult() + query.getMaxResults()));
	}
	
	return userList;
}
 
Example 19
Source File: TraceabilityDashboardServiceImpl.java    From Insights with Apache License 2.0 4 votes vote down vote up
private Map<String, List<JsonObject>> getMasterResponse(JsonObject response, JsonObject dataModel) {

		JsonArray finaltoolsArray = new JsonArray();
		// Master Map contains toolname as string and list of toolpayload .
		HashMap<String, List<JsonObject>> masterMap = new HashMap<>();
		LinkedHashMap<String, List<JsonObject>> sortedmasterMap = new LinkedHashMap<>();
		JsonArray responseArray = response.getAsJsonArray("results").getAsJsonArray().get(0).getAsJsonObject()
				.get("data").getAsJsonArray();
		int count = responseArray.size();
		for (int j = 0; j < count; j++) {
			List<JsonObject> toolsPayload = new ArrayList<JsonObject>();
			// find the toolname in neo4j response
			LOG.debug("Data From Neo4J has been loaded properly");
			JsonArray toolsArray = responseArray.get(j).getAsJsonObject().get("row").getAsJsonArray();
			String toolNameFromNeo4j = toolsArray.get(0).getAsString();
			// Get the response template of the specific tool from data model
			JsonObject toolPayloadFromDatamodel = dataModel.get(toolNameFromNeo4j).getAsJsonObject();
			if (toolPayloadFromDatamodel != null) {
				Set<Entry<String, JsonElement>> keyset = toolPayloadFromDatamodel.entrySet();
				int numOfObjectsPerTool = toolsArray.get(1).getAsJsonArray().size();
				for (int i = 0; i < numOfObjectsPerTool; i++) {
					JsonObject formattedJsonObject = new JsonObject();
					for (Map.Entry<String, JsonElement> toolKeyValueSetFromDataModel : keyset) {
						// Every tool is JsonArray so loop it if it has more than one element get
						// extract the value of the each key
						if (toolKeyValueSetFromDataModel.getKey().equals("order"))
							formattedJsonObject.addProperty(toolKeyValueSetFromDataModel.getKey(),
									toolKeyValueSetFromDataModel.getValue().toString());
						JsonElement propertyValFromNeo4j = toolsArray.get(1).getAsJsonArray().get(i).getAsJsonObject()
								.get(toolKeyValueSetFromDataModel.getValue().toString().replaceAll("\"", ""));
						if (propertyValFromNeo4j != null) {
							String neo4jValue = propertyValFromNeo4j.getAsString();
							if (toolKeyValueSetFromDataModel.getKey().equals("timestamp")) {
								int iEnd = propertyValFromNeo4j.getAsString().indexOf('.');
								if (iEnd != -1)
									neo4jValue = propertyValFromNeo4j.getAsString().substring(0, iEnd);
								else
									neo4jValue = propertyValFromNeo4j.getAsString();
							}
							formattedJsonObject.addProperty(toolKeyValueSetFromDataModel.getKey(), neo4jValue);
						}
					}
					/* Add toolStatus property explicitly if the object does not have it already */
					if (formattedJsonObject.get("toolstatus") == null)
						formattedJsonObject.addProperty("toolstatus", "Success");
					formattedJsonObject.addProperty("count", Integer.toString(numOfObjectsPerTool));
					toolsPayload.add(formattedJsonObject);
				}

				/* sort the tools payload with timestamp before adding into the mastermap */
				List<JsonObject> sortedPayload = sortToolsPayload(toolsPayload);
				/* prepare the summary */
				/* Add each tool list payload to mastermap with toolname as key */
				masterMap.put(toolNameFromNeo4j, sortedPayload);

			}
		}
		List<Map.Entry<String, List<JsonObject>>> list = new LinkedList<>(masterMap.entrySet());
		Collections.sort(list, new Comparator<Map.Entry<String, List<JsonObject>>>() {
			public int compare(Map.Entry<String, List<JsonObject>> o1, Map.Entry<String, List<JsonObject>> o2) {
				if(o1.getValue().get(0).has("order"))
				{
				return (Integer.valueOf(o1.getValue().get(0).get("order").getAsInt())
						.compareTo((Integer.valueOf(o2.getValue().get(0).get("order").getAsInt()))));
				}
				else
				{
					return -1;
				}
			}
		});
		for (Map.Entry<String, List<JsonObject>> entry : list) {
			sortedmasterMap.put(entry.getKey(), entry.getValue());
		}
		/* prepare the summary */
		JsonObject finalObj = new JsonObject();
		finalObj.add("data", finaltoolsArray);
		return sortedmasterMap;
	}
 
Example 20
Source File: SolrSearchProviderImpl.java    From swellrt with Apache License 2.0 4 votes vote down vote up
@Timed
@Override
public SearchResult search(final ParticipantId user, String query, int startAt, int numResults) {

  LOG.fine("Search query '" + query + "' from user: " + user + " [" + startAt + ", "
      + ((startAt + numResults) - 1) + "]");

  // Maybe should be changed in case other folders in addition to 'inbox' are
  // added.
  final boolean isAllQuery = isAllQuery(query);

  LinkedHashMultimap<WaveId, WaveletId> currentUserWavesView = LinkedHashMultimap.create();

  if (numResults > 0) {

    int start = startAt;
    int rows = Math.max(numResults, ROWS);

    /*-
     * "fq" stands for Filter Query. see
     * http://wiki.apache.org/solr/CommonQueryParameters#fq
     */
    String fq = buildFilterQuery(query, isAllQuery, user.getAddress(), sharedDomainParticipantId);

    try {
      while (true) {
        String solrQuery = buildCurrentSolrQuery(start, rows, fq);

        JsonArray docsJson = sendSearchRequest(solrQuery, extractDocsJsonFunction);

        addSearchResultsToCurrentWaveView(currentUserWavesView, docsJson);
        if (docsJson.size() < rows) {
          break;
        }
        start += rows;
      }
    } catch (Exception e) {
      LOG.warning("Failed to execute query: " + query);
      LOG.warning(e.getMessage());
      return digester.generateSearchResult(user, query, null);
    }
  }

  ensureWavesHaveUserDataWavelet(currentUserWavesView, user);

  LinkedHashMap<WaveId, WaveViewData> results =
      createResults(user, isAllQuery, currentUserWavesView);

  Collection<WaveViewData> searchResult =
      computeSearchResult(user, startAt, numResults, Lists.newArrayList(results.values()));
  LOG.info("Search response to '" + query + "': " + searchResult.size() + " results, user: "
      + user);

  return digester.generateSearchResult(user, query, searchResult);
}