Java Code Examples for java.util.List

The following are top voted examples for showing how to use java.util.List. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: elasticsearch-osem   File: AbstractOsemTest.java View source code 26 votes vote down vote up
protected Tweet getRandomTweet() {
    Tweet tweet = new Tweet();
    tweet.setId(randomLong());
    tweet.setImage(randomAsciiOfLengthBetween(100, 10000));
    tweet.setTweetDate(new Date());
    tweet.setTweetString(randomAsciiOfLengthBetween(100, 10000));
    tweet.setFlagged(randomBoolean());

    List<String> urls = new ArrayList<String>();
    for (int i = 0; i < randomIntBetween(10, 20); i ++) {
        urls.add(randomAsciiOfLengthBetween(10, 100));
    }
    tweet.setUrls(urls);

    tweet.setUser(getRandomUser());

    List<User> userList = new ArrayList<User>();
    for (int i = 0; i < randomIntBetween(10, 20); i ++) {
        userList.add(getRandomUser());
    }
    tweet.setMentionedUserList(userList);

    List<Date> specialDates = new ArrayList<Date>();
    for (int i = 0; i < randomIntBetween(10, 20); i ++) {
        specialDates.add(new Date());
    }
    tweet.setSpecialDates(specialDates);

    return tweet;
}
 
Example 2
Project: apache-james-mime4j-groundhog   File: Header.java View source code 12 votes vote down vote up
/**
 * Sets or replaces a field. This method is useful for header fields such as
 * Subject or Message-ID that should not occur more than once in a message.
 * 
 * If this <code>Header</code> does not already contain a header field of
 * the same name as the given field then it is added to the end of the list
 * of fields (same behavior as [email protected] #addField(Field)}). Otherwise the
 * first occurrence of a field with the same name is replaced by the given
 * field and all further occurrences are removed.
 * 
 * @param field the field to set.
 */
public void setField(Field field) {
    final String lowerCaseName = field.getName().toLowerCase();
    List<Field> l = fieldMap.get(lowerCaseName);
    if (l == null || l.isEmpty()) {
        addField(field);
        return;
    }

    l.clear();
    l.add(field);

    int firstOccurrence = -1;
    int index = 0;
    for (Iterator<Field> iterator = fields.iterator(); iterator.hasNext(); index++) {
        Field f = iterator.next();
        if (f.getName().equalsIgnoreCase(field.getName())) {
            iterator.remove();

            if (firstOccurrence == -1)
                firstOccurrence = index;
        }
    }

    fields.add(firstOccurrence, field);
}
 
Example 3
Project: funCKit   File: NewBrickListManager.java View source code 10 votes vote down vote up
private void removeAllExternalBrickTypes() {
    List<Integer> removed = new LinkedList<Integer>();

    for (ListIterator<Brick> it = newBrickList.listIterator(); it.hasNext();) {
        int index = it.nextIndex();
        Brick brick = it.next();
        if (listTypeMap.get(brick) == BrickListType.TYPE_EXTERNAL_COMPONENT) {
            removed.add(index);
            it.remove();
            listTypeMap.remove(brick);
        }
    }

    brickToFileMap.clear();

    int[] idxes = new int[removed.size()];
    for (ListIterator<Integer> it = removed.listIterator(); it.hasNext();) {
        idxes[it.nextIndex()] = it.next();
    }

    sessionModel.getInfo().setNewBrickListChanged(true);
    sessionModel.getInfo().setNewBrickListRemovedIndices(idxes);
    sessionModel.notifyObservers();

}
 
Example 4
Project: strongback-java   File: NewProject.java View source code 8 votes vote down vote up
protected static String combineAndEscape( List<String> lines, String strongbackHome ) throws IOException {
    StringBuilder sb = new StringBuilder();
    lines.forEach(str->{
        String replaced = str.replaceAll("STRONGBACKHOME",strongbackHome).replaceAll("    ", "\t");
        sb.append(replaced).append("\n");
    });
    return sb.toString();
}
 
Example 5
Project: sphereMiners   File: Physics.java View source code 7 votes vote down vote up
/**
 * Creates the initial tick for a simulation. This also deletes the previously
 * done simulation.
 *
 * @param playingAIs the list of players that should take part
 * @return the computed initial tick
 */
public Tick createInitialTick(List<Player> playingAIs) {
    aiSpheres.clear();
    spheresForAisNextTurn.clear();
    Position initalPos = new Position(constants.getFieldWidth()/2, constants.getFieldHeight()/2);
    double angle = 360.0/playingAIs.size();
    
    // b² = c² - a², c = 1 im Einheitskreis, a = sin Alpha * c im Einheitskreis
    // Strahlensatz: ZA zu BA = ZA' zu BA', c zu a = x*c zu x*a sodass x*a = 5 
    double a = Math.sin(angle/360*Math.PI);
    double radius = constants.getInitialDistance() / 2 / a;

    int i = 0;
    for (Player ai : playingAIs) {
        // create new sphere for current player
        MutableSphere sphere = new MutableSphere(constants, ai);
        Position addPos = new Position(radius * Math.cos(i * 2 * Math.PI / playingAIs.size()),
                                       radius * Math.sin(i * 2 * Math.PI / playingAIs.size()));

        // place modulo the usual position if it would be out of bounds
        Position spherePos = initalPos.add(addPos);
        if (spherePos.getX() < 0 || spherePos.getX() > constants.getFieldWidth()
            || spherePos.getY() < 0 || spherePos.getY() > constants.getFieldHeight()) {
            spherePos = new Position(spherePos.getX() % constants.getFieldWidth(),
                                     spherePos.getY() % constants.getFieldHeight());
        }

        sphere.setPosition(spherePos);

        aiSpheres.put(sphere, sphere.toImmutableSphere());
        i++;
    }
    createDots(constants.getDotAmount());

    spheresForAisNextTurn.addAll(aiSpheres.values());
    return snapshot();
}
 
Example 6
Project: lettuce   File: GeoCommandTest.java View source code 7 votes vote down vote up
@Test
public void georadiusWithArgs() throws Exception {

    prepareGeo();

    GeoArgs geoArgs = new GeoArgs().withHash().withCoordinates().withDistance().withCount(1).desc();

    List<GeoWithin<String>> result = redis.georadius(key, 8.665351, 49.553302, 5, GeoArgs.Unit.km, geoArgs);
    assertThat(result).hasSize(1);

    GeoWithin<String> weinheim = result.get(0);

    assertThat(weinheim.member).isEqualTo("Weinheim");
    assertThat(weinheim.geohash).isEqualTo(3666615932941099L);

    assertThat(weinheim.distance).isEqualTo(2.7882, offset(0.5));
    assertThat(weinheim.coordinates.x.doubleValue()).isEqualTo(8.663875, offset(0.5));
    assertThat(weinheim.coordinates.y.doubleValue()).isEqualTo(49.52825, offset(0.5));

    result = redis.georadius(key, 8.665351, 49.553302, 1, GeoArgs.Unit.km, new GeoArgs());
    assertThat(result).hasSize(1);

    GeoWithin<String> bahn = result.get(0);

    assertThat(bahn.member).isEqualTo("Bahn");
    assertThat(bahn.geohash).isNull();

    assertThat(bahn.distance).isNull();
    assertThat(bahn.coordinates).isNull();
}
 
Example 7
Project: aws-toolkit-eclipse   File: JdbcStatement.java View source code 7 votes vote down vote up
/**
 * @return The number of columns/attributes in the query
 */
public int getColumnNum() {
    int size = this.columns.size();

    List<String> pendings = JdbcStatement.this.conn.getPendingColumns(JdbcStatement.this.getDomainName());
    if (pendings != null && !pendings.isEmpty() && this.columns.isEmpty()) {
        ++size; // +1 for ItemName - special case when there is just freshly added attributes and there is no content in the domain
    }
    if (pendings != null) {
        pendings = new ArrayList<String>(pendings);
        pendings.removeAll(this.columns);
        size += pendings.size();
    }

    return size;
}
 
Example 8
Project: richfaces   File: AbstractOrderingComponent.java View source code 7 votes vote down vote up
protected boolean compareValues(Object previous, Object value) {
    if (previous == null && value != null) {
        return true;
    } else if (previous != null && value == null) {
        return true;
    } else if (previous == null) {
        return false;
    }

    List oldList;
    List newList;

    if (previous instanceof List) {
        oldList = (List) previous;
    } else {
        if (previous instanceof Object[]) {
            oldList = Arrays.asList(previous);
        } else {
            throw new IllegalArgumentException("Ordered List Components must be backed by a List or Array");
        }
    }

    if (value instanceof List) {
        newList = (List) value;
    } else {
        if (value instanceof Object[]) {
            newList = Arrays.asList(value);
        } else {
            throw new IllegalArgumentException("Ordered List Components must be backed by a List or Array");
        }
    }

    return !oldList.equals(newList);
}
 
Example 9
Project: java8-explorer   File: Main.java View source code 7 votes vote down vote up
public static void main(String[] args) throws IOException {
    String basePath = System.getProperty("basePath");

    System.out.println("parsing files from basePath: " + basePath);

    FileWalker fileWalker = new FileWalker();
    ExplorerResult result = fileWalker.walk(basePath);

    System.out.println(result.getStatistics());

    List<TypeInfo> typeInfos = result.getTypeInfos();
    typeInfos.sort((t1, t2) -> t1.getPackageName().compareTo(t2.getPackageName()));

    System.out.println("creating site");

    SiteCreator siteCreator = new SiteCreator();
    siteCreator.createSite(result);

    System.out.println("done");
}
 
Example 10
Project: lettuce   File: PooledClusterConnectionProvider.java View source code 6 votes vote down vote up
protected RedisAsyncConnectionImpl<K, V> getReadConnection(int slot) {
    RedisAsyncConnectionImpl<K, V> readerCandidates[];// avoid races when reconfiguring partitions.
    synchronized (stateLock) {
        readerCandidates = readers[slot];
    }

    if (readerCandidates == null) {
        RedisClusterNode master = partitions.getPartitionBySlot(slot);
        if (master == null) {
            throw new RedisException("Cannot determine a partition to read for slot " + slot + " (Partitions: "
                    + partitions + ")");
        }

        final List<RedisNodeDescription> candidates = getReadCandidates(master);
        List<RedisNodeDescription> selection = readFrom.select(new ReadFrom.Nodes() {
            @Override
            public List<RedisNodeDescription> getNodes() {
                return candidates;
            }

            @Override
            public Iterator<RedisNodeDescription> iterator() {
                return candidates.iterator();
            }
        });

        if (selection.isEmpty()) {
            throw new RedisException("Cannot determine a partition to read for slot " + slot + " (Partitions: "
                    + partitions + ") with setting " + readFrom);
        }

        readerCandidates = getReadFromConnections(selection);
        readers[slot] = readerCandidates;
    }

    // try working connections at first
    for (RedisAsyncConnectionImpl<K, V> readerCandidate : readerCandidates) {
        if (!readerCandidate.isOpen()) {
            continue;
        }
        return readerCandidate;
    }

    // fall-back to the first connection for same behavior as writing
    return readerCandidates[0];
}
 
Example 11
Project: lettuce   File: CommandHandler.java View source code 6 votes vote down vote up
private void cancelCommands(String message) {
    int size = 0;
    if (queue != null) {
        size += queue.size();
    }

    if (commandBuffer != null) {
        size += commandBuffer.size();
    }

    List<RedisCommand<K, V, ?>> toCancel = new ArrayList<RedisCommand<K, V, ?>>(size);

    if (queue != null) {
        toCancel.addAll(queue);
        queue.clear();
    }

    if (commandBuffer != null) {
        toCancel.addAll(commandBuffer);
        commandBuffer.clear();
    }
    sentTimes.clear();

    for (RedisCommand<K, V, ?> cmd : toCancel) {
        if (cmd.getOutput() != null) {
            cmd.getOutput().setError(message);
        }
        cmd.cancel(true);
    }
}
 
Example 12
Project: lettuce   File: ClusterSlotsParser.java View source code 6 votes vote down vote up
private static ClusterSlotRange parseRange(List<?> range) {
    Iterator<?> iterator = range.iterator();

    int from = Ints.checkedCast(getLongFromIterator(iterator, 0));
    int to = Ints.checkedCast(getLongFromIterator(iterator, 0));
    HostAndPort master = null;

    List<HostAndPort> slaves = Lists.newArrayList();
    if (iterator.hasNext()) {
        master = getHostAndPort(iterator);
    }

    while (iterator.hasNext()) {
        HostAndPort slave = getHostAndPort(iterator);
        if (slave != null) {
            slaves.add(slave);
        }
    }

    return new ClusterSlotRange(from, to, master, Collections.unmodifiableList(slaves));
}
 
Example 13
Project: iot-server-appliances   File: PolicyFilterImpl.java View source code 6 votes vote down vote up
/**
 * This method will extract the policies related a given roles list from the policy list available.
 *
 * @param policyList
 * @param roles
 * @return
 */
@Override
public List<Policy> extractPoliciesRelatedToRoles(List<Policy> policyList, List<String> roles) {

    List<Policy> policies = new ArrayList<Policy>();

    for (Policy policy : policyList) {
        List<String> roleList = policy.getRoles();

        for (String role : roleList) {
            if (roles.contains(role)) {
                policies.add(policy);
                break;
            }
        }
    }
    return policies;
}
 
Example 14
Project: raylew_algorithm   File: MaxK.java View source code 6 votes vote down vote up
/**
 * ????5??
 * @param lst
 * @return
 */
public static List<Integer> max5(List<Integer> lst) {
    if (lst.size() <= 5)
        return lst;

    int a = lst.remove(lst.size() - 1);
    List<Integer> b = max5(lst);

    for (int i = 0; i < b.size(); i++) {
        int t = b.get(i);
        if (a > t) {
            lst.set(i, a);
            a = t;
        }
    }

    return b;
}
 
Example 15
Project: aws-toolkit-eclipse   File: TargetFunctionSelectionPage.java View source code 6 votes vote down vote up
private int findDefaultFunction(List<String> functionNames) {
    if (this.defaultFunctionName == null) {
        return 0;
    }
    int defaultInd = functionNames.indexOf(this.defaultFunctionName);
    return defaultInd < 0 ? 0 : defaultInd;
}
 
Example 16
Project: richfaces   File: ExtendedDataTableRenderer.java View source code 6 votes vote down vote up
public RendererState(FacesContext context, UIDataTableBase table) {
    super(context);
    this.table = table;

    List<UIComponent> columns = getOrderedColumns(context);

    frozenColumnsSize = (Integer) table.getAttributes().get("frozenColumns");
    if (frozenColumnsSize < 0 || frozenColumnsSize >= columns.size()) {
        frozenColumnsSize = 0;
    }

    int count = Math.min(frozenColumnsSize, columns.size());
    List<UIComponent> frozenColumns = columns.subList(0, count);
    columns = columns.subList(count, columns.size());
    parts = new ArrayList<Part>(PartName.values().length);
    if (frozenColumns.size() > 0) {
        parts.add(new Part(PartName.frozen, frozenColumns));
    }
    if (columns.size() > 0) {
        parts.add(new Part(PartName.normal, columns));
    }
}
 
Example 17
Project: SOLR   File: QueryResultKey.java View source code 6 votes vote down vote up
public QueryResultKey(Query query, List<Query> filters, Sort sort, int nc_flags) {
  this.query = query;
  this.sort = sort;
  this.filters = filters;
  this.nc_flags = nc_flags;

  int h = query.hashCode();

  if (filters != null) h ^= filters.hashCode();

  sfields = (this.sort !=null) ? this.sort.getSort() : defaultSort;
  for (SortField sf : sfields) {
    // mix the bits so that sortFields are position dependent
    // so that a,b won't hash to the same value as b,a
    h ^= (h << 8) | (h >>> 25);   // reversible hash

    if (sf.getField() != null) h += sf.getField().hashCode();
    h += sf.getType();
    if (sf.getReverse()) h=~h;
    if (sf.getLocale()!=null) h+=sf.getLocale().hashCode();
    if (sf.getFactory()!=null) h+=sf.getFactory().hashCode();
  }

  hc = h;
}
 
Example 18
Project: virgo.kernel   File: StandardQuasiFramework.java View source code 6 votes vote down vote up
/**
 * [email protected]}
 */
@Override
public void commit() throws BundleException {
    synchronized (this.monitor) {
        if (this.otherBundles == null) {
            List<QuasiResolutionFailure> failures = resolve();
            if (!failures.isEmpty()) {
                throw new BundleException("Commit resolution failed: '" + failures.toString() + "'");
            }
        } else {
            try {
                Set<Long> installedQuasiBundles = installQuasiBundles();
                List<Bundle> installedDependencies = installOtherBundles(installedQuasiBundles);
                startBundles(installedDependencies);
            } catch (BundleException e) {
                uninstallQuasiBundles();
                throw e;
            }
        }
    }
}
 
Example 19
Project: javalang   File: FieldDeclarationComparator.java View source code 6 votes vote down vote up
@Override
public int compare(FieldDeclaration fd1, FieldDeclaration fd2) {
	if (fd1.getType().equals(fd2.getType())) {
		List<VariableDeclarator> vds = fd1.getVariables();
		List<VariableDeclarator> vds2 = fd2.getVariables();
		if (vds == null || vds.size() == 0 || vds2 == null
				|| vds2.size() == 0) {
			return -1;
		}
		if (vds.size() == vds2.size()) {
			if (vds.containsAll(vds2)) {
				return 0;
			}
		}
	}
	return -1;
}
 
Example 20
Project: BioWiki   File: StringUtils.java View source code 6 votes vote down vote up
public static String[] mergeStringArrays(String array1[], String array2[]) {
    if (array1 == null || array1.length == 0) {
        return array2;
    }
    if (array2 == null || array2.length == 0) {
        return array1;
    }
    List<String> array1List = Arrays.asList(array1);
    List<String> array2List = Arrays.asList(array2);
    List<String> result = new ArrayList<String>(array1List);
    List<String> tmp = new ArrayList<String>(array1List);
    tmp.retainAll(array2List);
    result.addAll(array2List);
    return ((String[]) result.toArray(new String[result.size()]));
}
 
Example 21
Project: jboss-dmr   File: ListModelValue.java View source code 6 votes vote down vote up
@Override
ModelValue protect() {
    final List<ModelNode> list = this.list;
    for (final ModelNode node : list) {
        node.protect();
    }
    return list.getClass() == ArrayList.class ? new ListModelValue(Collections.unmodifiableList(list)) : this;
}
 
Example 22
Project: au-proteus   File: XBee.java View source code 6 votes vote down vote up
/**
 * Synchronous method for sending an XBeeRequest and obtaining the 
 * corresponding response (response that has same frame id).
 * 
 * This method should only be called with requests that receive a response of
 * type XBeeFrameIdResponse and you should attempt to use a unique frame id (see getNextFrameId)
 * 
 * This method returns the first response object with a matching frame id within the timeout
 * period
 * 
 * TX requests send status responses (ACK) that indicate if the packet was delivered.  
 * In my brief testing with series 2 radios in a simple 2 radio network, I got a status 
 * response of ADDRESS_NOT_FOUND in about 3 seconds when my end device is powered off.  
 * Keep in mind that you'll want to make sure your timeout is always larger than this 
 * value in order to receive status responses.
 * 
 * NOTE: this method is thread-safe because it's not possible for the user to easily
 * make it thread safe and perform well 
 * 
 * TODO responses received during synchronous send should not be added to the packetList
 * 
 * @param xbeeRequest
 * 
 * @return
 * @throws XBeeException 
 * @throws IOException
 * @throws InterruptedException
 * @throws XBeeTimeoutException 
 */
public XBeeResponse sendSynchronous(final XBeeRequest xbeeRequest, int timeout) throws XBeeTimeoutException, XBeeException {

	if (xbeeRequest.getFrameId() == XBeeRequest.NO_RESPONSE_FRAME_ID) {
		throw new XBeeException("Frame Id cannot be 0 for a synchronous call -- it will always timeout as there is no response!");
	}		

	PacketListener pl = null;
	
	try {
		XBeePacket txPacket = xbeeRequest.getXBeePacket();

		final List<XBeeResponse> responseList = new ArrayList<XBeeResponse>();
		
		// TODO verify that there is no possibility the response could be received in the milliseconds before sending packet
		
		pl = new PacketListener() {
			// TODO handle error response as well
			public void processResponse(XBeeResponse response) {
				if (response instanceof XBeeFrameIdResponse && ((XBeeFrameIdResponse)response).getFrameId() == xbeeRequest.getFrameId()) {
					// frame id matches -- yay we found it
					responseList.add(response);
					
					synchronized(responseList) {
						responseList.notify();	
					}
					
				}
			}
		};
		
		this.addPacketListener(pl);
		
		// this makes it thread safe -- prevents multiple threads from writing to output stream simultaneously
		synchronized (sendPacketBlock) {
			this.sendPacket(txPacket);	
		}

		synchronized (responseList) {
			try {
				responseList.wait(timeout);
			} catch (InterruptedException e) { }
		}
		
		if (responseList.size() == 0) {
			// we didn't find a matching packet
			throw new XBeeTimeoutException();
		}
		
		return (XBeeResponse) responseList.get(0);
	} catch (IOException io) {
		throw new XBeeException(io);
	} finally {
		if (pl != null) {
			this.removePacketListener(pl);
		}
	}
}
 
Example 23
Project: eGov   File: PositionMasterService.java View source code 6 votes vote down vote up
public List<Position> getPositionsForDeptDesigAndName(final Long departmentId, final Long designationId,
        final Date fromDate, final Date toDate, final String posName) {
    List<Position> posList = new ArrayList<Position>();
    final List<Assignment> assignList = assignmentService.getAssignmentsByDeptDesigAndDates(departmentId,
            designationId, fromDate, toDate);
    posList = positionMasterRepository
            .findByDeptDesig_Department_IdAndDeptDesig_Designation_IdAndNameContainingIgnoreCase(departmentId,
                    designationId, posName);
    for (final Assignment assign : assignList)
        posList.removeIf(m -> m.getId() == assign.getPosition().getId());
    return posList;
}
 
Example 24
Project: bennu   File: FileSystemLogRepository.java View source code 6 votes vote down vote up
/**
 * [email protected]}
 */
@Override
public Stream<ExecutionLog> executionsFor(String taskName, Optional<String> start, int max) {
    String id;
    if (start.isPresent()) {
        id = start.get();
    } else {
        JsonObject index = readIndexJson();
        if (!index.has(taskName)) {
            return Stream.empty();
        }
        id = index.get(taskName).getAsString();
    }
    List<ExecutionLog> logs = new ArrayList<>(Math.min(max, 100));
    while (id != null && max > 0) {
        Optional<JsonObject> optional = readJson(logFileFor(taskName, id));
        if (optional.isPresent()) {
            JsonObject json = optional.get();
            id = json.has("previous") ? json.get("previous").getAsString() : null;
            logs.add(new ExecutionLog(json));
            max--;
        } else {
            break;
        }
    }
    return logs.stream();
}
 
Example 25
Project: sslcertx   File: MySQLDatabaseMetaData.java View source code 5 votes vote down vote up
public static ResultSet getImportedKeys(String tableDef, String tableName, String catalog, MySQLConnection c) throws ParseException {
   String[] columnNames  = {
           "PKTABLE_CAT","PKTABLE_SCHEM", "PKTABLE_NAME",
           "PKCOLUMN_NAME","FKTABLE_CAT","FKTABLE_SCHEM",
           "FKTABLE_NAME", "FKCOLUMN_NAME", "KEY_SEQ",
           "UPDATE_RULE","DELETE_RULE","FK_NAME",
           "PK_NAME","DEFERRABILITY"
           };
   MySQLType.Type [] columnTypes =  {
           MySQLType.Type.VARCHAR, MySQLType.Type.NULL, MySQLType.Type.VARCHAR,
           MySQLType.Type.VARCHAR, MySQLType.Type.VARCHAR, MySQLType.Type.NULL,
           MySQLType.Type.VARCHAR, MySQLType.Type.VARCHAR, MySQLType.Type.SMALLINT,
           MySQLType.Type.SMALLINT, MySQLType.Type.SMALLINT, MySQLType.Type.VARCHAR,
           MySQLType.Type.NULL,MySQLType.Type.SMALLINT};

   String[] parts = tableDef.split("\n");

   List<String[]> data = new ArrayList<String[]>();

   for (String p:parts) {
        //System.out.println("--" + p);
        p = p.trim();
        if (!p.startsWith("CONSTRAINT") && !p.contains("FOREIGN KEY"))
            continue;
        char [] s = p.toCharArray();

        Identifier constraintName = new Identifier();
        Identifier pkTable = new Identifier();
        List<Identifier> foreignKeyCols = new ArrayList<Identifier>();
        List<Identifier> primaryKeyCols = new ArrayList<Identifier>();

        int pos = skipKeyword(s, 0, "CONSTRAINT");
        pos = parseIdentifier(s, pos, constraintName);
        pos = skipKeyword(s, pos, "FOREIGN KEY");
        pos = parseIdentifierList(s, pos, foreignKeyCols);
        pos = skipKeyword(s, pos, "REFERENCES");
        pos = parseIdentifier(s, pos, pkTable);
        parseIdentifierList(s, pos, primaryKeyCols);
        if (primaryKeyCols.size() != foreignKeyCols.size()) {
            throw new ParseException(tableDef,0);
        }
        int onUpdateReferenceAction = DatabaseMetaData.importedKeyRestrict;
        int onDeleteReferenceAction = DatabaseMetaData.importedKeyRestrict;


       for (String referenceAction : new String[] {"RESTRICT", "CASCADE",  "SET NULL", "NO ACTION"}) {
            if (p.contains("ON UPDATE " + referenceAction))
                onUpdateReferenceAction = getImportedKeyAction(referenceAction);
            if (p.contains("ON DELETE " + referenceAction))
                onDeleteReferenceAction =  getImportedKeyAction(referenceAction);
       }

       for(int i = 0; i < primaryKeyCols.size(); i++) {

           String[] row = new String[columnNames.length];
           row[0] =  pkTable.schema;
           if (row[0] == null) {
               row[0] = catalog;
           }
           row[1] = null;
           row[2] = pkTable.name;
           row[3] = primaryKeyCols.get(i).name;
           row[4] = catalog;
           row[5] = null;
           row[6] = tableName;
           row[7] = foreignKeyCols.get(i).name;
           row[8] = Integer.toString(i+1);
           row[9] = Integer.toString(onUpdateReferenceAction);
           row[10] = Integer.toString(onDeleteReferenceAction);
           row[11] = constraintName.name;
           row[12] = null;
           row[13] = Integer.toString(DatabaseMetaData.importedKeyInitiallyImmediate);
           data.add(row);
       }
   }
   String[][] arr = data.toArray(new String[0][]);

   /* Sort array by PKTABLE_CAT, PKTABLE_NAME, and KEY_SEQ.*/
   Arrays.sort(arr, new Comparator<String[]>() {
       @Override
       public int compare(String[] row1, String[] row2) {
           int result = row1[0].compareTo(row2[0]);   //PKTABLE_CAT
           if (result == 0){
              result = row1[2].compareTo(row2[2]);   //PKTABLE_NAME
              if (result == 0) {
                  result = row1[8].length() - row2[8].length();  // KEY_SEQ
                  if (result == 0)
                      result =  row1[8].compareTo(row2[8]);
              }
           }
           return result;
       }
   });
   ResultSet ret =  MySQLResultSet.createResultSet(columnNames,columnTypes,arr, c.getProtocol());
   return ret;
}
 
Example 26
Project: wso2-synapse   File: SALoadbalanceEndpoint.java View source code 5 votes vote down vote up
private void sendMessageOnCurrentSession(String sessionID, List<Endpoint> endpoints, MessageContext synCtx) {
            
    // get the next endpoint in the endpoint sequence
    Endpoint endpoint = null;

    boolean invalidSequence = false;
    if (endpoints.isEmpty()) {
        invalidSequence = true;
    } else {
        if (endpoints.contains(this)) {
            // This situation will come only if this endpoint is referred as an indirect endpoint.
            //  All the path before this SAL endpoint are ignored.
            int length = endpoints.size();
            if (length > 1) {
                
                int beginIndex = endpoints.lastIndexOf(this) + 1;
                if (beginIndex == length) {
                    invalidSequence = true;
                } else {
                    endpoints = endpoints.subList(beginIndex, length);
                    if (!endpoints.isEmpty()) {
                        endpoint = endpoints.remove(0);
                    } else {
                        invalidSequence = true;
                    }
                }
            } else {
                invalidSequence = true;
            }

        } else {
            endpoint = endpoints.remove(0);
        }
    }

    if (invalidSequence) {
        informFailure(synCtx, SynapseConstants.ENDPOINT_SAL_INVALID_PATH,
                "Invalid endpoint sequence " + endpoints + " for session with id " + sessionID);
        return;
    }
    // endpoints given by session dispatchers may not be active. therefore, we have check
    // it here.
    if (endpoint != null && endpoint.readyToSend()) {
        if (log.isDebugEnabled()) {
            log.debug("Using the endpoint " + endpoint + " for sending the message");
        }
        synCtx.pushFaultHandler(this);
        endpoint.send(synCtx);
    } else {
        informFailure(synCtx, SynapseConstants.ENDPOINT_SAL_NOT_READY,
                "The endpoint " + endpoint + " on the session with id " +
                        sessionID + " is not ready.");
    }
}