Example usage for java.util ArrayList toString

List of usage examples for java.util ArrayList toString

Introduction

In this page you can find the example usage for java.util ArrayList toString.

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:com.cmput301.classproject.Model.Tasks.JSONServer.java

/**
 * This will retrieve all tasks by using Gson to retrieve the ids of each
 * task from the server. The results will be stored in a ServerData object
 * and the ids will be added to an array.
 * /*from  w  w w  . j a va 2 s. c  o m*/
 * After retrieving all the ids, we use the internal getTask(String id)
 * method to get the task and add it to the tasks array
 * 
 * @return An ArrayList<Task>. The list will be empty if there are no tasks
 */
public ArrayList<Task> getAllTasks() {
    ArrayList<Task> tasks = new ArrayList<Task>();
    ArrayList<ServerData> ids = new ArrayList<ServerData>();

    try {

        // Do a list action to get the id's
        List<BasicNameValuePair> values = new ArrayList<BasicNameValuePair>();

        // This is equivalent to doing:
        // http://path?action=post&summary=desc&content=content
        values.add(new BasicNameValuePair("action", "list"));

        httpPost.setEntity(new UrlEncodedFormEntity(values));
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            InputStream is = entity.getContent();
            String jsonString = convertStreamToString(is);
            Type collectionType = new TypeToken<Collection<ServerData>>() {
            }.getType();
            ids = gson.fromJson(jsonString, collectionType);
            // List the id's
            for (ServerData i : ids) {
                LOGGER.log(Level.INFO, "ID: " + i.getId());
                tasks.add(getTask(i.getId()));
            }
        }

        LOGGER.log(Level.INFO, ids.toString());
        // EntityUtils.consume(entity);

    } catch (Exception ex) {
        LOGGER.log(Level.SEVERE, ex.getMessage());
        ex.printStackTrace();
    }

    for (Task t : tasks) {
        LOGGER.log(Level.INFO, "Task: " + t.toString());
    }

    return tasks;

}

From source file:org.sead.repositories.reference.RefRepository.java

private ObjectNode getChildren(ObjectNode resultNode, File indexFile, CountingInputStream cis, Long oreFileSize,
        long curPos, ArrayList<String> entries, ArrayList<Long> offsets)
        throws JsonParseException, JsonMappingException, IOException {

    ArrayList<String> childIds = new ArrayList<String>();
    JsonNode children = resultNode.get("Has Part");
    if (children.isArray()) {
        for (JsonNode child : children) {
            childIds.add(child.textValue());
        }/* w ww.  j a v a  2  s  .  c o m*/
    } else {
        System.out.println("Has Part not an array");
        childIds.add(children.textValue());
    }
    ArrayNode aggregates = mapper.createArrayNode();
    for (String name : childIds) {
        aggregates.add(getItem(name, indexFile, cis, false, oreFileSize, curPos, entries, offsets));
        curPos = cis.getByteCount();
        log.trace("curPos updated to " + curPos + " after reading: " + name);

    }
    log.trace("Child Ids: " + childIds.toString());
    resultNode.set("aggregates", aggregates);
    return resultNode;

}

From source file:com.spoiledmilk.cykelsuperstier.break_rote.LocalTrainData.java

private static void getTimesForWeekend(int hour, int minute, ArrayList<ITransportationInfo> times,
        JsonNode timeTableNode, int index1, int index2, int numOfStations, JsonNode dataNodeArray) {
    ArrayList<TimeData> allTimes = new ArrayList<TimeData>();
    for (int i = 0; i < timeTableNode.size(); i++) {
        JsonNode intervalNode = timeTableNode.get(i);
        try {/*w ww  .j  a va  2s  .  c  om*/
            double currentTime = ((double) hour) + ((double) minute) / 100d;
            double startInterval = intervalNode.get("start-time").asDouble();
            double endInterval = intervalNode.get("end-time").asDouble();
            if (endInterval < 1.0)
                endInterval += 24.0;
            if (currentTime >= startInterval && currentTime <= endInterval) {
                JsonNode dataNode = dataNodeArray.get(i);
                int[] minutesArray = new int[dataNode.size()];
                for (int j = 0; j < minutesArray.length; j++) {
                    minutesArray[j] = dataNode.get(j).asInt();
                }
                int currentHour = hour;
                int currentIndex = 0;
                int count = 0;
                while (currentHour <= endInterval && count < 3 && currentIndex < minutesArray.length) {
                    double time1 = minutesArray[currentIndex + index1];
                    double time2 = minutesArray[currentIndex + index2];
                    if (time1 < 0 || time2 < 0)
                        continue;
                    time1 /= 100d;
                    time1 += currentHour;
                    time2 /= 100d;
                    time2 += currentHour;
                    if (time2 < time1)
                        time2 += 1.0;
                    allTimes.add(new TimeData(time1, time2));
                    currentHour++;
                    count++;
                    currentIndex += numOfStations;
                }
            }
        } catch (Exception e) {
            LOG.e(e.getLocalizedMessage());
        }
    }

    // sort the list
    for (int i = 0; i < allTimes.size() - 1; i++) {
        for (int j = i + 1; j < allTimes.size(); j++) {
            TimeData td1 = allTimes.get(i);
            TimeData td2 = allTimes.get(j);
            if (td1.stationAtime > td2.stationAtime) {
                allTimes.set(i, td2);
                allTimes.set(j, td1);
            }
        }
    }

    LOG.d("sorted times = " + allTimes.toString());

    // return the 3 results
    for (int i = 0; i < 3 && i < allTimes.size(); i++) {
        TimeData temp = allTimes.get(i);
        int time = 0;
        int minutes1 = (int) ((temp.stationAtime - (double) ((int) temp.stationAtime)) * 100);
        int minutes2 = (int) ((temp.stationBtime - (double) ((int) temp.stationBtime)) * 100);
        time = (((int) temp.stationBtime) - ((int) temp.stationAtime)) * 60;
        if (minutes2 >= minutes1)
            time = minutes2 - minutes1;
        else {
            time += 60 - minutes1 + minutes2;
            time -= 60;
        }
        String formattedTime1 = (((int) temp.stationAtime) < 10 ? "0" + ((int) temp.stationAtime)
                : "" + ((int) temp.stationAtime)) + ":" + (minutes1 < 10 ? "0" + minutes1 : "" + minutes1);
        String formattedTime2 = (((int) temp.stationBtime) < 10 ? "0" + ((int) temp.stationBtime)
                : "" + ((int) temp.stationBtime)) + ":" + (minutes2 < 10 ? "0" + minutes2 : "" + minutes2);
        times.add(new LocalTrainData(formattedTime1, formattedTime2, time));
    }

}

From source file:com.spoiledmilk.cykelsuperstier.break_rote.LocalTrainData.java

private static void getTimesForWeekdays(int hour, int minute, ArrayList<ITransportationInfo> times,
        JsonNode timeTableNode, int index1, int index2, int numOfStations) {
    ArrayList<TimeData> allTimes = new ArrayList<TimeData>();
    for (int i = 0; i < timeTableNode.size(); i++) {
        JsonNode intervalNode = timeTableNode.get(i);
        try {//  ww  w  .  ja v a 2  s .c  o  m
            double currentTime = ((double) hour) + ((double) minute) / 100d;
            double startInterval = intervalNode.get("start-time").asDouble();
            double endInterval = intervalNode.get("end-time").asDouble();
            if (endInterval < 1.0)
                endInterval += 24.0;
            if (currentTime >= startInterval && currentTime <= endInterval) {
                JsonNode dataNode = intervalNode.get("data");
                int[] minutesArray = new int[dataNode.size()];
                for (int j = 0; j < minutesArray.length; j++) {
                    minutesArray[j] = dataNode.get(j).asInt();
                }
                int currentHour = hour;
                int currentIndex = 0;
                int count = 0;
                while (currentHour <= endInterval && count < 3 && currentIndex < minutesArray.length) {
                    double time1 = minutesArray[currentIndex + index1];
                    double time2 = minutesArray[currentIndex + index2];
                    if (time1 < 0 || time2 < 0)
                        continue;
                    time1 /= 100d;
                    time1 += currentHour;
                    time2 /= 100d;
                    time2 += currentHour;
                    if (time2 < time1)
                        time2 += 1.0;
                    allTimes.add(new TimeData(time1, time2));
                    currentHour++;
                    count++;
                    currentIndex += numOfStations;
                }
            }
        } catch (Exception e) {
            LOG.e(e.getLocalizedMessage());
        }
    }

    // sort the list
    for (int i = 0; i < allTimes.size() - 1; i++) {
        for (int j = i + 1; j < allTimes.size(); j++) {
            TimeData td1 = allTimes.get(i);
            TimeData td2 = allTimes.get(j);
            if (td1.stationAtime > td2.stationAtime) {
                allTimes.set(i, td2);
                allTimes.set(j, td1);
            }
        }
    }

    LOG.d("sorted times = " + allTimes.toString());

    // return the 3 results
    for (int i = 0; i < 3 && i < allTimes.size(); i++) {
        TimeData temp = allTimes.get(i);
        int time = 0;
        int minutes1 = (int) ((temp.stationAtime - (double) ((int) temp.stationAtime)) * 100);
        int minutes2 = (int) ((temp.stationBtime - (double) ((int) temp.stationBtime)) * 100);
        time = (((int) temp.stationBtime) - ((int) temp.stationAtime)) * 60;
        if (minutes2 >= minutes1)
            time = minutes2 - minutes1;
        else {
            time += 60 - minutes1 + minutes2;
            time -= 60;
        }
        String formattedTime1 = (((int) temp.stationAtime) < 10 ? "0" + ((int) temp.stationAtime)
                : "" + ((int) temp.stationAtime)) + ":" + (minutes1 < 10 ? "0" + minutes1 : "" + minutes1);
        String formattedTime2 = (((int) temp.stationBtime) < 10 ? "0" + ((int) temp.stationBtime)
                : "" + ((int) temp.stationBtime)) + ":" + (minutes2 < 10 ? "0" + minutes2 : "" + minutes2);
        times.add(new LocalTrainData(formattedTime1, formattedTime2, time));
    }

}

From source file:com.mobiperf_library.measurements.PingTask.java

/** 
 * Use the HTTP Head method to emulate ping. The measurement from this method can be 
 * substantially (2x) greater than the first two methods and inaccurate. This is because, 
 * depending on the implementing of the destination web server, either a quick HTTP
 * response is replied or some actual heavy lifting will be done in preparing the response
 * *//*from w  w w .  ja  va  2s.  c  o m*/
private MeasurementResult executeHttpPingTask() throws MeasurementError {
    long pingStartTime = 0;
    long pingEndTime = 0;
    ArrayList<Double> rrts = new ArrayList<Double>();
    PingDesc pingTask = (PingDesc) this.measurementDesc;
    String errorMsg = "";
    MeasurementResult result = null;

    try {
        long totalPingDelay = 0;

        URL url = new URL("http://" + pingTask.target);

        int timeOut = (int) (3000 * (double) pingTask.pingTimeoutSec / Config.PING_COUNT_PER_MEASUREMENT);

        for (int i = 0; i < Config.PING_COUNT_PER_MEASUREMENT; i++) {
            pingStartTime = System.currentTimeMillis();
            HttpURLConnection httpClient = (HttpURLConnection) url.openConnection();
            httpClient.setRequestProperty("Connection", "close");
            httpClient.setRequestMethod("HEAD");
            httpClient.setReadTimeout(timeOut);
            httpClient.setConnectTimeout(timeOut);
            httpClient.connect();
            pingEndTime = System.currentTimeMillis();
            httpClient.disconnect();
            rrts.add((double) (pingEndTime - pingStartTime));
            this.progress = 100 * i / Config.PING_COUNT_PER_MEASUREMENT;
            broadcastProgressForUser(progress);
        }
        Logger.i("HTTP get ping succeeds");
        Logger.i("RTT is " + rrts.toString());
        double packetLoss = 1 - ((double) rrts.size() / (double) Config.PING_COUNT_PER_MEASUREMENT);
        result = constructResult(rrts, packetLoss, Config.PING_COUNT_PER_MEASUREMENT, PING_METHOD_HTTP);
    } catch (MalformedURLException e) {
        Logger.e(e.getMessage());
        errorMsg += e.getMessage() + "\n";
    } catch (IOException e) {
        Logger.e(e.getMessage());
        errorMsg += e.getMessage() + "\n";
    }
    if (result != null) {
        return result;
    } else {
        Logger.i("HTTP get ping fails");
        throw new MeasurementError(errorMsg);
    }
}

From source file:com.mobiperf.measurements.PingTask.java

/** 
 * Use the HTTP Head method to emulate ping. The measurement from this method can be 
 * substantially (2x) greater than the first two methods and inaccurate. This is because, 
 * depending on the implementing of the destination web server, either a quick HTTP
 * response is replied or some actual heavy lifting will be done in preparing the response
 * *///from  w w w  . ja  v a2s. c om
private MeasurementResult executeHttpPingTask() throws MeasurementError {
    long pingStartTime = 0;
    long pingEndTime = 0;
    ArrayList<Double> rrts = new ArrayList<Double>();
    PingDesc pingTask = (PingDesc) this.measurementDesc;
    String errorMsg = "";
    MeasurementResult result = null;

    try {
        long totalPingDelay = 0;

        URL url = new URL("http://" + pingTask.target);

        int timeOut = (int) (3000 * (double) pingTask.pingTimeoutSec / Config.PING_COUNT_PER_MEASUREMENT);

        for (int i = 0; i < Config.PING_COUNT_PER_MEASUREMENT; i++) {
            pingStartTime = System.currentTimeMillis();
            HttpURLConnection httpClient = (HttpURLConnection) url.openConnection();
            httpClient.setRequestProperty("Connection", "close");
            httpClient.setRequestMethod("HEAD");
            httpClient.setReadTimeout(timeOut);
            httpClient.setConnectTimeout(timeOut);
            httpClient.connect();
            pingEndTime = System.currentTimeMillis();
            httpClient.disconnect();
            rrts.add((double) (pingEndTime - pingStartTime));
            this.progress = 100 * i / Config.PING_COUNT_PER_MEASUREMENT;
            broadcastProgressForUser(progress);
        }
        Logger.i("HTTP get ping succeeds");
        Logger.i("RTT is " + rrts.toString());
        double packetLoss = 1 - ((double) rrts.size() / (double) Config.PING_COUNT_PER_MEASUREMENT);
        result = constructResult(rrts, packetLoss, Config.PING_COUNT_PER_MEASUREMENT, PING_METHOD_HTTP);
        dataConsumed += pingTask.packetSizeByte * Config.PING_COUNT_PER_MEASUREMENT * 2;

    } catch (MalformedURLException e) {
        Logger.e(e.getMessage());
        errorMsg += e.getMessage() + "\n";
    } catch (IOException e) {
        Logger.e(e.getMessage());
        errorMsg += e.getMessage() + "\n";
    }
    if (result != null) {
        return result;
    } else {
        Logger.i("HTTP get ping fails");
        throw new MeasurementError(errorMsg);
    }
}

From source file:citation_prediction.CitationCore.java

/**
 * This function runs the Newton-Raphson function on an interval from .1 to 10 returning a list of
 * all the unique solutions.//w  w w.  j a v  a  2 s.c  o  m
 * 
 * @param data The citation data in days.
 * @param step The step you would like to use to step through the interval of .1 to 10.
 * @param m The average number of new references contained in each paper for a journal.
 * @return A list of list containing the WSB solutions.
 */
private static ArrayList<LinkedHashMap<String, Double>> newtonRaphson_ConvergenceTest(double[][] data,
        double start, double mu_guess, double sigma_guess, double step, double m, boolean wasAlreadyRun) {

    CitationCore cc = new CitationCore();

    String[] matrix_headers = { "mu0", "sigma0", "lambda", "mu", "sigma", "iteration" };
    ArrayList<ArrayList<Double>> matrix = new ArrayList<ArrayList<Double>>(100);
    ArrayList<LinkedHashMap<String, Double>> solutions = new ArrayList<LinkedHashMap<String, Double>>(100);
    ArrayList<Double> lambdas = new ArrayList<Double>();

    for (double mu0 = start; mu0 < (mu_guess + 2); mu0 += step) {
        for (double sigma0 = start; sigma0 < (sigma_guess + 2); sigma0 += step) {
            LinkedHashMap<String, Double> answer = cc.newtonRaphson(data, mu0, sigma0, m);

            if (answer.get("lambda") != null) {
                ArrayList<Double> row = new ArrayList<Double>();

                row.add(mu0);
                row.add(sigma0);
                row.add(answer.get("lambda"));
                row.add(answer.get("mu"));
                row.add(answer.get("sigma"));
                row.add(answer.get("iterations"));

                matrix.add(row);

                boolean isUnique = true;
                for (double l : lambdas) {
                    if ((answer.get("lambda") < 0) || Math.abs(l - answer.get("lambda")) < 1e-2) {
                        isUnique = false;
                        break;
                    }
                }
                if (isUnique) {
                    LinkedHashMap<String, Double> s = new LinkedHashMap<String, Double>();
                    s.put("lambda", answer.get("lambda"));
                    s.put("mu", answer.get("mu"));
                    s.put("sigma", answer.get("sigma"));

                    solutions.add(s);
                }

                lambdas.add(answer.get("lambda"));
            }
        }
    }

    printMatrix(matrix, matrix_headers);
    System.out.println("Unique Solutions:");
    System.out.println(solutions.toString());

    if (!wasAlreadyRun && solutions.isEmpty())
        return newtonRaphson_ConvergenceTest(data, start, mu_guess, sigma_guess, .1, m, true);
    else
        return solutions;
}

From source file:com.pinterest.arcee.aws.EC2HostInfoDAOImpl.java

@Override
public List<String> getRunningInstances(List<String> runningIds) throws Exception {
    HashSet<String> ids = new HashSet<>(runningIds);
    ArrayList<String> resultIds = new ArrayList<>();
    while (!ids.isEmpty()) {
        DescribeInstancesRequest request = new DescribeInstancesRequest();
        request.setInstanceIds(ids);// w  w  w . j ava  2  s .  c om
        Filter filter = new Filter("instance-state-code", Arrays.asList(RUNNING_CODE));
        request.setFilters(Arrays.asList(filter));
        try {
            do {
                DescribeInstancesResult results = ec2Client.describeInstances(request);
                List<Reservation> reservations = results.getReservations();
                for (Reservation reservation : reservations) {
                    for (Instance instance : reservation.getInstances()) {
                        resultIds.add(instance.getInstanceId());
                    }
                }
                if (StringUtils.isEmpty(results.getNextToken())) {
                    break;
                }

                request = new DescribeInstancesRequest();
                request.setNextToken(results.getNextToken());
            } while (true);
            LOG.debug("Cannot find the following ids in AWS:", ids);
            return resultIds;
        } catch (AmazonServiceException ex) {
            // if the error code is not instance not found. return the terminated list we've already got.
            ids.removeAll(handleInvalidInstanceId(ex));
        } catch (AmazonClientException ex) {
            LOG.error(String.format("Get AmazonClientException, exit with terminiatedHost %s",
                    resultIds.toString()), ex);
            throw new Exception(String.format("Get AmazonClientException, exit with terminiatedHost %s",
                    resultIds.toString()), ex);
        }
    }
    return resultIds;
}

From source file:org.codice.ddf.catalog.ui.metacard.MetacardApplication.java

@Override
public void init() {
    get("/metacardtype", (req, res) -> util.getJson(util.getMetacardTypeMap()));

    get("/metacard/:id", (req, res) -> {
        String id = req.params(":id");
        return util.metacardToJson(id);
    });//from   w  w  w. java  2  s.  c  o  m

    get("/metacard/:id/attribute/validation", (req, res) -> {
        String id = req.params(":id");
        return util.getJson(validator.getValidation(util.getMetacardById(id)));
    });

    get("/metacard/:id/validation", (req, res) -> {
        String id = req.params(":id");
        return util.getJson(validator.getFullValidation(util.getMetacardById(id)));
    });

    post("/prevalidate", APPLICATION_JSON, (req, res) -> {
        Map<String, Object> stringObjectMap = GSON.fromJson(util.safeGetBody(req), MAP_STRING_TO_OBJECT_TYPE);
        MetacardImpl metacard = new MetacardImpl();
        stringObjectMap.keySet().stream()
                .map(s -> new AttributeImpl(s, (List<Serializable>) stringObjectMap.get(s)))
                .forEach(metacard::setAttribute);
        return util.getJson(validator.getValidation(metacard));
    });

    post("/metacards", APPLICATION_JSON, (req, res) -> {
        List<String> ids = GSON.fromJson(util.safeGetBody(req), LIST_STRING);
        List<Metacard> metacards = util.getMetacardsWithTagById(ids, "*").entrySet().stream()
                .map(Map.Entry::getValue).map(Result::getMetacard).collect(Collectors.toList());

        return util.metacardsToJson(metacards);
    });

    delete("/metacards", APPLICATION_JSON, (req, res) -> {
        List<String> ids = GSON.fromJson(util.safeGetBody(req), LIST_STRING);
        DeleteResponse deleteResponse = catalogFramework
                .delete(new DeleteRequestImpl(new ArrayList<>(ids), Metacard.ID, null));
        if (deleteResponse.getProcessingErrors() != null && !deleteResponse.getProcessingErrors().isEmpty()) {
            res.status(500);
            return ImmutableMap.of("message", "Unable to archive metacards.");
        }

        return ImmutableMap.of("message", "Successfully archived metacards.");
    }, util::getJson);

    patch("/metacards", APPLICATION_JSON, (req, res) -> {
        String body = util.safeGetBody(req);
        List<MetacardChanges> metacardChanges = GSON.fromJson(body, METACARD_CHANGES_LIST_TYPE);

        UpdateResponse updateResponse = patchMetacards(metacardChanges, getSubjectIdentifier());
        if (updateResponse.getProcessingErrors() != null && !updateResponse.getProcessingErrors().isEmpty()) {
            res.status(500);
            return updateResponse.getProcessingErrors();
        }

        return body;
    });

    put("/validate/attribute/:attribute", TEXT_PLAIN, (req, res) -> {
        String attribute = req.params(":attribute");
        String value = util.safeGetBody(req);
        return util.getJson(validator.validateAttribute(attribute, value));
    });

    get("/history/:id", (req, res) -> {
        String id = req.params(":id");
        List<Result> queryResponse = getMetacardHistory(id);
        if (queryResponse.isEmpty()) {
            res.status(204);
            return "[]";
        }
        List<HistoryResponse> response = queryResponse.stream().map(Result::getMetacard)
                .map(mc -> new HistoryResponse(mc.getId(),
                        (String) mc.getAttribute(MetacardVersion.EDITED_BY).getValue(),
                        (Date) mc.getAttribute(MetacardVersion.VERSIONED_ON).getValue()))
                .sorted(Comparator.comparing(HistoryResponse::getVersioned)).collect(Collectors.toList());
        return util.getJson(response);
    });

    get("/history/revert/:id/:revertid", (req, res) -> {
        String id = req.params(":id");
        String revertId = req.params(":revertid");

        Metacard versionMetacard = util.getMetacardById(revertId);

        List<Result> queryResponse = getMetacardHistory(id);
        if (queryResponse == null || queryResponse.isEmpty()) {
            throw new NotFoundException("Could not find metacard with id: " + id);
        }

        Optional<Metacard> contentVersion = queryResponse.stream().map(Result::getMetacard)
                .filter(mc -> getVersionedOnDate(mc).isAfter(getVersionedOnDate(versionMetacard))
                        || getVersionedOnDate(mc).equals(getVersionedOnDate(versionMetacard)))
                .filter(mc -> CONTENT_ACTIONS.contains(Action.ofMetacard(mc)))
                .filter(mc -> mc.getResourceURI() != null)
                .filter(mc -> ContentItem.CONTENT_SCHEME.equals(mc.getResourceURI().getScheme()))
                .sorted(Comparator.comparing((Metacard mc) -> util
                        .parseToDate(mc.getAttribute(MetacardVersion.VERSIONED_ON).getValue())))
                .findFirst();

        if (!contentVersion.isPresent()) {
            /* no content versions, just restore metacard */
            revertMetacard(versionMetacard, id, false);
        } else {
            revertContentandMetacard(contentVersion.get(), versionMetacard, id);
        }
        return util.metacardToJson(MetacardVersionImpl.toMetacard(versionMetacard, types));
    });

    get("/associations/:id", (req, res) -> {
        String id = req.params(":id");
        return util.getJson(associated.getAssociations(id));
    });

    put("/associations/:id", (req, res) -> {
        String id = req.params(":id");
        String body = util.safeGetBody(req);
        List<Associated.Edge> edges = GSON.fromJson(body, ASSOCIATED_EDGE_LIST_TYPE);
        associated.putAssociations(id, edges);
        return body;
    });

    post("/subscribe/:id", (req, res) -> {
        String userid = getSubjectIdentifier();
        String email = getSubjectEmail();
        if (isEmpty(email)) {
            throw new NotFoundException(
                    "Unable to subscribe to workspace, " + userid + " has no email address.");
        }
        String id = req.params(":id");
        subscriptions.addEmail(id, email);
        return ImmutableMap.of("message", String.format("Successfully subscribed to id = %s.", id));
    }, util::getJson);

    post("/unsubscribe/:id", (req, res) -> {
        String userid = getSubjectIdentifier();
        String email = getSubjectEmail();
        if (isEmpty(email)) {
            throw new NotFoundException(
                    "Unable to un-subscribe from workspace, " + userid + " has no email address.");
        }
        String id = req.params(":id");
        if (StringUtils.isEmpty(req.body())) {
            subscriptions.removeEmail(id, email);
            return ImmutableMap.of("message", String.format("Successfully un-subscribed to id = %s.", id));
        } else {
            String body = req.body();
            AttributeChange attributeChange = GSON.fromJson(body, ATTRIBUTE_CHANGE_TYPE);
            subscriptions.removeEmails(id, new HashSet<>(attributeChange.getValues()));
            return ImmutableMap.of("message", String.format("Successfully un-subscribed emails %s id = %s.",
                    attributeChange.getValues().toString(), id));
        }
    }, util::getJson);

    get("/workspaces/:id", (req, res) -> {
        String id = req.params(":id");
        String email = getSubjectEmail();
        Metacard metacard = util.getMetacardById(id);

        // NOTE: the isEmpty is to guard against users with no email (such as guest).
        boolean isSubscribed = !isEmpty(email) && subscriptions.getEmails(metacard.getId()).contains(email);

        return ImmutableMap.builder().putAll(transformer.transform(metacard)).put("subscribed", isSubscribed)
                .build();
    }, util::getJson);

    get("/workspaces", (req, res) -> {
        String email = getSubjectEmail();
        // NOTE: the isEmpty is to guard against users with no email (such as guest).
        Set<String> ids = isEmpty(email) ? Collections.emptySet() : subscriptions.getSubscriptions(email);

        return util.getMetacardsByTag(WorkspaceConstants.WORKSPACE_TAG).entrySet().stream()
                .map(Map.Entry::getValue).map(Result::getMetacard).map(metacard -> {
                    boolean isSubscribed = ids.contains(metacard.getId());
                    try {
                        return ImmutableMap.builder().putAll(transformer.transform(metacard))
                                .put("subscribed", isSubscribed).build();
                    } catch (RuntimeException e) {
                        LOGGER.debug(
                                "Could not transform metacard. WARNING: This indicates there is invalid data in the system. Metacard title: '{}', id:'{}'",
                                metacard.getTitle(), metacard.getId(), e);
                    }
                    return null;
                }).filter(Objects::nonNull).collect(Collectors.toList());
    }, util::getJson);

    post("/workspaces", APPLICATION_JSON, (req, res) -> {
        Map<String, Object> incoming = GSON.fromJson(util.safeGetBody(req), MAP_STRING_TO_OBJECT_TYPE);

        List<Metacard> queries = ((List<Map<String, Object>>) incoming
                .getOrDefault(WorkspaceConstants.WORKSPACE_QUERIES, Collections.emptyList())).stream()
                        .map(transformer::transform).collect(Collectors.toList());

        queryMetacardsHandler.create(Collections.emptyList(), queries);

        Metacard saved = saveMetacard(transformer.transform(incoming));
        Map<String, Object> response = transformer.transform(saved);

        res.status(201);
        return util.getJson(response);
    });

    put("/workspaces/:id", APPLICATION_JSON, (req, res) -> {
        String id = req.params(":id");

        WorkspaceMetacardImpl existingWorkspace = workspaceService.getWorkspaceMetacard(id);
        List<String> existingQueryIds = existingWorkspace.getQueries();

        Map<String, Object> updatedWorkspace = GSON.fromJson(util.safeGetBody(req), MAP_STRING_TO_OBJECT_TYPE);

        List<Metacard> updatedQueryMetacards = ((List<Map<String, Object>>) updatedWorkspace
                .getOrDefault("queries", Collections.emptyList())).stream().map(transformer::transform)
                        .collect(Collectors.toList());

        List<String> updatedQueryIds = updatedQueryMetacards.stream().map(Metacard::getId)
                .collect(Collectors.toList());

        List<QueryMetacardImpl> existingQueryMetacards = workspaceService.getQueryMetacards(existingWorkspace);

        queryMetacardsHandler.create(existingQueryIds, updatedQueryMetacards);
        queryMetacardsHandler.delete(existingQueryIds, updatedQueryIds);
        queryMetacardsHandler.update(existingQueryIds, existingQueryMetacards, updatedQueryMetacards);

        List<Map<String, String>> queryIdModel = updatedQueryIds.stream()
                .map(queryId -> ImmutableMap.of("id", queryId)).collect(Collectors.toList());

        updatedWorkspace.put("queries", queryIdModel);
        Metacard metacard = transformer.transform(updatedWorkspace);
        metacard.setAttribute(new AttributeImpl(Core.ID, id));
        Metacard updated = updateMetacard(id, metacard);

        return transformer.transform(updated);
    }, util::getJson);

    delete("/workspaces/:id", APPLICATION_JSON, (req, res) -> {
        String id = req.params(":id");
        WorkspaceMetacardImpl workspace = workspaceService.getWorkspaceMetacard(id);

        String[] queryIds = workspace.getQueries().toArray(new String[0]);

        if (queryIds.length > 0) {
            catalogFramework.delete(new DeleteRequestImpl(queryIds));
        }

        catalogFramework.delete(new DeleteRequestImpl(id));

        subscriptions.removeSubscriptions(id);
        return ImmutableMap.of("message", "Successfully deleted.");
    }, util::getJson);

    get("/workspaces/:id/queries", (req, res) -> {
        String workspaceId = req.params(":id");
        WorkspaceMetacardImpl workspace = workspaceService.getWorkspaceMetacard(workspaceId);

        List<String> queryIds = workspace.getQueries();

        return util.getMetacardsWithTagById(queryIds, QUERY_TAG).values().stream().map(Result::getMetacard)
                .map(transformer::transform).collect(Collectors.toList());
    }, util::getJson);

    get("/enumerations/metacardtype/:type", APPLICATION_JSON, (req, res) -> {
        return util.getJson(enumExtractor.getEnumerations(req.params(":type")));
    });

    get("/enumerations/attribute/:attribute", APPLICATION_JSON, (req, res) -> {
        return util.getJson(enumExtractor.getAttributeEnumerations(req.params(":attribute")));
    });

    get("/localcatalogid", (req, res) -> {
        return String.format("{\"%s\":\"%s\"}", "local-catalog-id", catalogFramework.getId());
    });

    post("/transform/csv", APPLICATION_JSON, (req, res) -> {
        String body = util.safeGetBody(req);
        CsvTransform queryTransform = GSON.fromJson(body, CsvTransform.class);
        Map<String, Object> transformMap = GSON.fromJson(body, MAP_STRING_TO_OBJECT_TYPE);
        queryTransform.setMetacards((List<Map<String, Object>>) transformMap.get("metacards"));

        List<Result> metacards = queryTransform.getTransformedMetacards(types, attributeRegistry).stream()
                .map(ResultImpl::new).collect(Collectors.toList());

        Set<String> matchedHiddenFields = Collections.emptySet();
        if (queryTransform.isApplyGlobalHidden()) {
            matchedHiddenFields = getHiddenFields(metacards);
        }

        SourceResponseImpl response = new SourceResponseImpl(null, metacards, Long.valueOf(metacards.size()));

        Map<String, Serializable> arguments = ImmutableMap.<String, Serializable>builder()
                .put("hiddenFields",
                        new HashSet<>(Sets.union(matchedHiddenFields, queryTransform.getHiddenFields())))
                .put("columnOrder", new ArrayList<>(queryTransform.getColumnOrder()))
                .put("aliases", new HashMap<>(queryTransform.getColumnAliasMap())).build();

        BinaryContent content = csvQueryResponseTransformer.transform(response, arguments);

        String acceptEncoding = req.headers("Accept-Encoding");
        // Very naive way to handle accept encoding, does not respect full spec
        boolean shouldGzip = StringUtils.isNotBlank(acceptEncoding)
                && acceptEncoding.toLowerCase().contains("gzip");

        // Respond with content
        res.type("text/csv");
        String attachment = String.format("attachment;filename=export-%s.csv", Instant.now().toString());
        res.header("Content-Disposition", attachment);
        if (shouldGzip) {
            res.raw().addHeader("Content-Encoding", "gzip");
        }

        try ( //
                OutputStream servletOutputStream = res.raw().getOutputStream();
                InputStream resultStream = content.getInputStream()) {
            if (shouldGzip) {
                try (OutputStream gzipServletOutputStream = new GZIPOutputStream(servletOutputStream)) {
                    IOUtils.copy(resultStream, gzipServletOutputStream);
                }
            } else {
                IOUtils.copy(resultStream, servletOutputStream);
            }
        }
        return "";
    });

    post("/annotations", (req, res) -> {
        Map<String, Object> incoming = GSON.fromJson(util.safeGetBody(req), MAP_STRING_TO_OBJECT_TYPE);
        String workspaceId = incoming.get("workspace").toString();
        String queryId = incoming.get("parent").toString();
        String annotation = incoming.get("note").toString();
        String user = getSubjectIdentifier();
        if (user == null) {
            res.status(401);
            return util.getResponseWrapper(ERROR_RESPONSE_TYPE,
                    "You are not authorized to create notes! A user email is required. "
                            + "Please ensure you are logged in and/or have a valid email registered in the system.");
        }
        if (StringUtils.isBlank(annotation)) {
            res.status(400);
            return util.getResponseWrapper(ERROR_RESPONSE_TYPE, "No annotation!");
        }
        NoteMetacard noteMetacard = new NoteMetacard(queryId, user, annotation);

        Metacard workspaceMetacard = util.findWorkspace(workspaceId);

        if (workspaceMetacard == null) {
            res.status(404);
            return util.getResponseWrapper(ERROR_RESPONSE_TYPE, "Cannot find the workspace metacard!");
        }

        util.copyAttributes(workspaceMetacard, SECURITY_ATTRIBUTES, noteMetacard);

        Metacard note = saveMetacard(noteMetacard);

        SecurityLogger.auditWarn("Attaching an annotation to a resource: resource={} annotation={}",
                SecurityUtils.getSubject(), workspaceId, noteMetacard.getId());

        Map<String, String> responseNote = noteUtil.getResponseNote(note);
        if (responseNote == null) {
            res.status(500);
            return util.getResponseWrapper(ERROR_RESPONSE_TYPE, "Cannot serialize note metacard to json!");
        }
        return util.getResponseWrapper(SUCCESS_RESPONSE_TYPE, util.getJson(responseNote));
    });

    get("/annotations/:queryid", (req, res) -> {
        String queryId = req.params(":queryid");

        List<Metacard> retrievedMetacards = noteUtil.getAssociatedMetacardsByTwoAttributes(
                NoteConstants.PARENT_ID, Core.METACARD_TAGS, queryId, "note");
        ArrayList<String> getResponse = new ArrayList<>();
        retrievedMetacards.sort(Comparator.comparing(Metacard::getCreatedDate));
        for (Metacard metacard : retrievedMetacards) {
            Map<String, String> responseNote = noteUtil.getResponseNote(metacard);
            if (responseNote != null) {
                getResponse.add(util.getJson(responseNote));
            }
        }
        return util.getResponseWrapper(SUCCESS_RESPONSE_TYPE, getResponse.toString());
    });

    put("/annotations/:id", APPLICATION_JSON, (req, res) -> {
        Map<String, Object> incoming = GSON.fromJson(util.safeGetBody(req), MAP_STRING_TO_OBJECT_TYPE);
        String noteMetacardId = req.params(":id");
        String note = incoming.get("note").toString();
        Metacard metacard;
        try {
            metacard = util.getMetacardById(noteMetacardId);
        } catch (NotFoundException e) {
            LOGGER.debug("Note metacard was not found for updating. id={}", noteMetacardId);
            res.status(404);
            return util.getResponseWrapper(ERROR_RESPONSE_TYPE, "Note metacard was not found!");
        }

        Attribute attribute = metacard.getAttribute(Core.METACARD_OWNER);
        if (attribute != null && attribute.getValue() != null
                && !attribute.getValue().equals(getSubjectEmail())) {
            res.status(401);
            return util.getResponseWrapper(ERROR_RESPONSE_TYPE, "Owner of note metacard is invalid!");
        }
        metacard.setAttribute(new AttributeImpl(NoteConstants.COMMENT, note));
        metacard = updateMetacard(metacard.getId(), metacard);
        Map<String, String> responseNote = noteUtil.getResponseNote(metacard);
        return util.getResponseWrapper(SUCCESS_RESPONSE_TYPE, util.getJson(responseNote));
    });

    delete("/annotations/:id", (req, res) -> {
        String noteToDeleteMetacardId = req.params(":id");
        Metacard metacard;
        try {
            metacard = util.getMetacardById(noteToDeleteMetacardId);
        } catch (NotFoundException e) {
            LOGGER.debug("Note metacard was not found for deleting. id={}", noteToDeleteMetacardId);
            res.status(404);
            return util.getResponseWrapper(ERROR_RESPONSE_TYPE, "Note metacard was not found!");
        }
        Attribute attribute = metacard.getAttribute(Core.METACARD_OWNER);
        if (attribute != null && attribute.getValue() != null
                && !attribute.getValue().equals(getSubjectEmail())) {
            res.status(401);
            return util.getResponseWrapper(ERROR_RESPONSE_TYPE, "Owner of note metacard is invalid!");
        }
        DeleteResponse deleteResponse = catalogFramework.delete(new DeleteRequestImpl(noteToDeleteMetacardId));
        if (deleteResponse.getDeletedMetacards() != null && !deleteResponse.getDeletedMetacards().isEmpty()) {
            Map<String, String> responseNote = noteUtil
                    .getResponseNote(deleteResponse.getDeletedMetacards().get(0));
            return util.getResponseWrapper(SUCCESS_RESPONSE_TYPE, util.getJson(responseNote));
        }
        res.status(500);
        return util.getResponseWrapper(ERROR_RESPONSE_TYPE, "Could not delete note metacard!");
    });

    after((req, res) -> {
        res.type(APPLICATION_JSON);
    });

    exception(IngestException.class, (ex, req, res) -> {
        LOGGER.debug("Failed to ingest metacard", ex);
        res.status(404);
        res.header(CONTENT_TYPE, APPLICATION_JSON);
        res.body(util.getJson(ImmutableMap.of("message", UPDATE_ERROR_MESSAGE)));
    });

    exception(NotFoundException.class, (ex, req, res) -> {
        LOGGER.debug("Failed to find metacard.", ex);
        res.status(404);
        res.header(CONTENT_TYPE, APPLICATION_JSON);
        res.body(util.getJson(ImmutableMap.of("message", ex.getMessage())));
    });

    exception(NumberFormatException.class, (ex, req, res) -> {
        res.status(400);
        res.header(CONTENT_TYPE, APPLICATION_JSON);
        res.body(util.getJson(ImmutableMap.of("message", "Invalid values for numbers")));
    });

    exception(EntityTooLargeException.class, util::handleEntityTooLargeException);

    exception(IOException.class, util::handleIOException);

    exception(RuntimeException.class, util::handleRuntimeException);
}

From source file:com.caju.uheer.app.services.infrastructure.ContactablesLoaderCallbacks.java

@Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) {
    final ArrayList<String> infoAndName = new ArrayList<String>();
    try {//from ww w .  j a va 2 s. c  o  m
        for (int i = 0; i < usersFound.length(); i++) {
            infoAndName.add(usersFound.getJSONObject(i).getString("name"));
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    LocationManager locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
    LocationListener locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            Location geoPointLocation = new Location("geoPoint");
            try {
                infoAndName.clear();
                for (int i = 0; i < usersFound.length(); i++) {
                    String appendedText = "";
                    if (!usersFound.getJSONObject(i).has("channel")) {
                        geoPointLocation.setLongitude(usersFound.getJSONObject(i).getDouble("lon"));
                        geoPointLocation.setLatitude(usersFound.getJSONObject(i).getDouble("lat"));
                        float distance = location.distanceTo(geoPointLocation) / 1000;
                        appendedText = String.format("%.1f", distance) + "Km";
                    } else {
                        appendedText = usersFound.getJSONObject(i).getString("channel");
                    }
                    infoAndName.add(appendedText + usersFound.getJSONObject(i).getString("name"));
                    Log.e("infoandname", infoAndName.toString() + infoAndName.get(0) + infoAndName.get(1));
                    Toast.makeText(mContext, infoAndName.toString() + infoAndName.get(0) + infoAndName.get(1),
                            Toast.LENGTH_LONG).show();

                    // infoAndName tem a informacao de distancia ou canal e o nome. Precisa editar
                    //essa parte de baixo pra usar o infoAndName.
                    ArrayList<String> friendsEmails = new ArrayList<>();

                    friendsEmails.addAll(infoAndName);

                    friendsEmails = new ArrayList<>();
                    for (ArrayList<String> array : ServerInformation.getAllActiveListeners()) {
                        friendsEmails.addAll(array);
                        while (friendsEmails.contains(connectedEmail))
                            friendsEmails.remove(connectedEmail);
                    }
                    EmailListAdapter listAdapter = new EmailListAdapter(mContext, R.layout.adapter_email_list,
                            friendsEmails);
                    ListView emails = (ListView) ((Activity) mContext)
                            .findViewById(R.id.gps_friends_from_drawer);
                    emails.setAdapter(listAdapter);

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    };

    // Minimum of 2 minutes between checks (120000 milisecs).
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 120000, 0, locationListener);
}