Example usage for java.util LinkedList add

List of usage examples for java.util LinkedList add

Introduction

In this page you can find the example usage for java.util LinkedList add.

Prototype

public boolean add(E e) 

Source Link

Document

Appends the specified element to the end of this list.

Usage

From source file:edu.umd.cfar.lamp.viper.geometry.BoundingBox.java

/**
 * Gets a set of boxes which covers all and only the pixels covered by
 * <code>A</code> and <code>B</code>.
 * //  w  w  w . j a  v  a 2 s  . c om
 * @param A
 *            a set of boxes to union with
 * @param B
 *            a set of boxes to union with
 * @return a set of boxes corresponding to the region shared by A and B
 */
public static BoundingBox union(BoundingBox A, BoundingBox B) {
    BoundingBox temp = new BoundingBox();
    LinkedList aList;
    temp.composed = true;
    int x = Math.min(A.rect.x, B.rect.x);
    int y = Math.min(A.rect.y, B.rect.y);
    int x2 = Math.max(A.rect.x + A.rect.width, B.rect.x + B.rect.width);
    int y2 = Math.max(A.rect.y + A.rect.height, B.rect.y + B.rect.height);

    temp.rect = new Rectangle(x, y, x2, y2);

    if (A.composed)
        aList = (LinkedList) A.pieces.clone();
    else {
        aList = new LinkedList();
        aList.add(A);
    }

    if (B.composed)
        temp = B.copy();
    else {
        temp.pieces = new LinkedList();
        temp.pieces.add(B.copy());
        temp.composed = true;
    }

    ListIterator iter = aList.listIterator(0);
    while (iter.hasNext()) {
        BoundingBox child = (BoundingBox) iter.next();
        Iterator ti = temp.pieces.iterator();
        LinkedList childRemains = null;

        /* remove an offending piece of the child */
        while (ti.hasNext() && (null == (childRemains = ((BoundingBox) ti.next()).subtractFrom(child))))
            ;

        /*
         * Add the broken pieces into the list and break back to top loop
         * remove the offending rectangle and replace it with its shards,
         * then clean up those.
         */
        if (childRemains != null) {
            ti = childRemains.iterator();
            iter.remove();
            while (ti.hasNext()) {
                iter.add(ti.next());
                iter.previous();
            }
        }
    }
    temp.pieces.addAll(aList);
    temp.simplify();
    return (temp);
}

From source file:com.textocat.textokit.commons.cpe.JdbcCollectionReader.java

private List<DbTuple> queryBatch(int offset, int limit) throws SQLException, IOException {
    queryStatement.setInt(offsetParamIndex, offset);
    queryStatement.setInt(limitParamIndex, limit);
    ResultSet rs = queryStatement.executeQuery();
    try {//from  ww  w  .  j  a v  a2  s .c om
        LinkedList<DbTuple> result = newLinkedList();
        while (rs.next()) {
            result.add(toTuple(rs));
        }
        return ImmutableList.copyOf(result);
    } finally {
        rs.close();
    }
}

From source file:com.google.gerrit.server.account.CreateAccount.java

@Override
public Response<AccountInfo> apply(TopLevelResource rsrc, AccountInput input)
        throws BadRequestException, ResourceConflictException, UnprocessableEntityException, OrmException,
        IOException, ConfigInvalidException {
    if (input == null) {
        input = new AccountInput();
    }/*from  w  w w.j  a v a  2s  . c  o m*/
    if (input.username != null && !username.equals(input.username)) {
        throw new BadRequestException("username must match URL");
    }

    if (!username.matches(Account.USER_NAME_PATTERN)) {
        throw new BadRequestException(
                "Username '" + username + "'" + " must contain only letters, numbers, _, - or .");
    }

    Set<AccountGroup.Id> groups = parseGroups(input.groups);

    Account.Id id = new Account.Id(db.nextAccountId());

    AccountExternalId extUser = new AccountExternalId(id,
            new AccountExternalId.Key(AccountExternalId.SCHEME_USERNAME, username));

    if (input.httpPassword != null) {
        extUser.setPassword(input.httpPassword);
    }

    if (db.accountExternalIds().get(extUser.getKey()) != null) {
        throw new ResourceConflictException("username '" + username + "' already exists");
    }
    if (input.email != null) {
        if (db.accountExternalIds().get(getEmailKey(input.email)) != null) {
            throw new UnprocessableEntityException("email '" + input.email + "' already exists");
        }
        if (!EmailValidator.getInstance().isValid(input.email)) {
            throw new BadRequestException("invalid email address");
        }
    }

    LinkedList<AccountExternalId> externalIds = new LinkedList<>();
    externalIds.add(extUser);
    for (AccountExternalIdCreator c : externalIdCreators) {
        externalIds.addAll(c.create(id, username, input.email));
    }

    try {
        db.accountExternalIds().insert(externalIds);
    } catch (OrmDuplicateKeyException duplicateKey) {
        throw new ResourceConflictException("username '" + username + "' already exists");
    }

    if (input.email != null) {
        AccountExternalId extMailto = new AccountExternalId(id, getEmailKey(input.email));
        extMailto.setEmailAddress(input.email);
        try {
            db.accountExternalIds().insert(Collections.singleton(extMailto));
        } catch (OrmDuplicateKeyException duplicateKey) {
            try {
                db.accountExternalIds().delete(Collections.singleton(extUser));
            } catch (OrmException cleanupError) {
                // Ignored
            }
            throw new UnprocessableEntityException("email '" + input.email + "' already exists");
        }
    }

    Account a = new Account(id, TimeUtil.nowTs());
    a.setFullName(input.name);
    a.setPreferredEmail(input.email);
    db.accounts().insert(Collections.singleton(a));

    for (AccountGroup.Id groupId : groups) {
        AccountGroupMember m = new AccountGroupMember(new AccountGroupMember.Key(id, groupId));
        auditService.dispatchAddAccountsToGroup(currentUser.get().getAccountId(), Collections.singleton(m));
        db.accountGroupMembers().insert(Collections.singleton(m));
    }

    if (input.sshKey != null) {
        try {
            authorizedKeys.addKey(id, input.sshKey);
            sshKeyCache.evict(username);
        } catch (InvalidSshKeyException e) {
            throw new BadRequestException(e.getMessage());
        }
    }

    accountCache.evictByUsername(username);
    byEmailCache.evict(input.email);
    indexer.index(id);

    AccountLoader loader = infoLoader.create(true);
    AccountInfo info = loader.get(id);
    loader.fill();
    return Response.created(info);
}

From source file:com.cloud.agent.resource.virtualnetwork.ConfigHelper.java

private static List<ConfigItem> generateConfig(RemoteAccessVpnCfgCommand cmd) {
    LinkedList<ConfigItem> cfg = new LinkedList<>();
    String args = "";
    if (cmd.isCreate()) {
        args += "-r ";
        args += cmd.getIpRange();//  w w  w.j a  va 2s  .c om
        args += " -p ";
        args += cmd.getPresharedKey();
        args += " -s ";
        args += cmd.getVpnServerIp();
        args += " -l ";
        args += cmd.getLocalIp();
        args += " -c ";
    } else {
        args += "-d ";
        args += " -s ";
        args += cmd.getVpnServerIp();
    }
    args += " -C " + cmd.getLocalCidr();
    args += " -i " + cmd.getPublicInterface();
    cfg.add(new ScriptConfigItem(VRScripts.VPN_L2TP, args));
    return cfg;
}

From source file:exploration.rendezvous.MultiPointRendezvousStrategy.java

public static List<NearRVPoint> SampleEnvironmentPoints(RealAgent ag, double density) {
    LinkedList<NearRVPoint> genPoints = generateSobolPoints(ag.getOccupancyGrid(), density);
    //add base station to it. Could also add any special points here as well
    NearRVPoint base = new NearRVPoint(ag.getTeammate(SimConstants.BASE_STATION_TEAMMATE_ID).getX(),
            ag.getTeammate(SimConstants.BASE_STATION_TEAMMATE_ID).getY());
    genPoints.add(base);

    return genPoints;
}

From source file:com.spmadden.jnfsn.NFSNDns.java

public DNSResourceRecord[] getResourceRecords(final String name, final String type, final String data)
        throws APIException {
    try {//w w  w .j ava  2s  .  co  m
        final String url = getURL("listRRs");
        final HTTPConnection conn = new HTTPConnection(url, RequestMethod.POST, generator);

        if (name != null) {
            conn.addFormField("name", name);
        }
        if (type != null && !"".equals(type)) {
            conn.addFormField("type", type);
        }
        if (data != null && !"".equals(data)) {
            conn.addFormField("data", data);
        }

        final String value = NetUtils.consumeAll(conn.getDataStream());
        LOG.debug("JSON: " + value);

        final JSONArray arr = new JSONArray(value);
        final LinkedList<DNSResourceRecord> rrs = new LinkedList<>();
        for (int i = 0; i < arr.length(); ++i) {
            rrs.add(DNSResourceRecord.fromJSONObject(arr.getJSONObject(i)));
        }

        return rrs.toArray(new DNSResourceRecord[rrs.size()]);
    } catch (IOException e) {
        LOG.error(e);
    } catch (JSONException e) {
        LOG.error(e);
    }
    return null;
}

From source file:de.elggconnect.elggconnectclient.webservice.StatusUser.java

/**
 * handle the StatusUser JSON Response and store it into the StatusManager
 * <p>//from  w  w  w.  j  a v a2  s  .c o  m
 * Remove the old Data and fill it with new one
 *
 * @param result
 */
private void handleStatusUserResponse(JSONArray result) {

    LinkedList<JSONObject> statusUserObjectList = new LinkedList<>();

    //Save JSON Objects from result array
    for (Object aResult : result) {
        JSONObject object = (JSONObject) aResult;
        statusUserObjectList.add((JSONObject) object.get("object"));
    }

    //Clear StatusUserObjects
    StatusUserManager.getInstance().getStatusUserObjects().clear();

    //save all UserStatus objects
    statusUserObjectList.forEach(this::saveStatusUserObject);

}

From source file:net.dv8tion.jda.core.handle.GuildMemberUpdateHandler.java

private List<Role> toRolesList(GuildImpl guild, JSONArray array) {
    LinkedList<Role> roles = new LinkedList<>();
    for (int i = 0; i < array.length(); i++) {
        final long id = array.getLong(i);
        Role r = guild.getRolesMap().get(id);
        if (r != null) {
            roles.add(r);
        } else {//  w  ww .  j a v  a 2s.  co  m
            api.getEventCache().cache(EventCache.Type.ROLE, id, () -> {
                handle(responseNumber, allContent);
            });
            EventCache.LOG
                    .debug("Got GuildMember update but one of the Roles for the Member is not yet cached.");
            return null;
        }
    }
    return roles;
}

From source file:at.bitfire.davdroid.resource.WebDavCollection.java

@SuppressWarnings("unchecked")
public Resource[] multiGet(Resource[] resources)
        throws URISyntaxException, IOException, DavException, HttpException {
    try {//from  w  w w.  j  a  va  2  s  .c  o  m
        if (resources.length == 1)
            return new Resource[] { get(resources[0]) };

        Log.i(TAG, "Multi-getting " + resources.length + " remote resource(s)");

        LinkedList<String> names = new LinkedList<>();
        for (Resource resource : resources)
            names.add(resource.getName());

        LinkedList<T> foundResources = new LinkedList<>();
        collection.multiGet(multiGetType(), names.toArray(new String[names.size()]));
        if (collection.getMembers() == null)
            throw new DavNoContentException();

        for (WebDavResource member : collection.getMembers()) {
            T resource = newResourceSkeleton(member.getName(), member.getProperties().getETag());
            try {
                if (member.getContent() != null) {
                    @Cleanup
                    InputStream is = new ByteArrayInputStream(member.getContent());
                    resource.parseEntity(is, null, getDownloader());
                    foundResources.add(resource);
                } else
                    Log.e(TAG, "Ignoring entity without content");
            } catch (InvalidResourceException e) {
                Log.e(TAG, "Ignoring unparseable entity in multi-response", e);
            }
        }

        return foundResources.toArray(new Resource[foundResources.size()]);
    } catch (InvalidResourceException e) {
        Log.e(TAG, "Couldn't parse entity from GET", e);
    }

    return new Resource[0];
}

From source file:com.granita.icloudcalsync.resource.RemoteCollection.java

@SuppressWarnings("unchecked")
public Resource[] multiGet(Resource[] resources)
        throws URISyntaxException, IOException, DavException, HttpException {
    try {/*from  www . ja  v a2  s. c o m*/
        if (resources.length == 1)
            return (T[]) new Resource[] { get(resources[0]) };

        Log.i(TAG, "Multi-getting " + resources.length + " remote resource(s)");

        LinkedList<String> names = new LinkedList<String>();
        for (Resource resource : resources)
            names.add(resource.getName());

        LinkedList<T> foundResources = new LinkedList<T>();
        collection.multiGet(multiGetType(), names.toArray(new String[0]));
        if (collection.getMembers() == null)
            throw new DavNoContentException();

        for (WebDavResource member : collection.getMembers()) {
            T resource = newResourceSkeleton(member.getName(), member.getETag());
            try {
                if (member.getContent() != null) {
                    @Cleanup
                    InputStream is = new ByteArrayInputStream(member.getContent());
                    resource.parseEntity(is, getDownloader());
                    foundResources.add(resource);
                } else
                    Log.e(TAG, "Ignoring entity without content");
            } catch (InvalidResourceException e) {
                Log.e(TAG, "Ignoring unparseable entity in multi-response", e);
            }
        }

        return foundResources.toArray(new Resource[0]);
    } catch (InvalidResourceException e) {
        Log.e(TAG, "Couldn't parse entity from GET", e);
    }

    return new Resource[0];
}