Java Examples for java.util.LinkedList

The following java examples will help you to understand the usage of java.util.LinkedList. These source code samples are taken from different open source projects.

Example 1
Project: j2objc-master  File: LinkedListTest.java View source code
/**
	 * @tests java.util.LinkedList#add(int, java.lang.Object)
	 */
public void test_addILjava_lang_Object() {
    // Test for method void java.util.LinkedList.add(int, java.lang.Object)
    Object o;
    ll.add(50, o = "Test");
    assertTrue("Failed to add Object>: " + ll.get(50).toString(), ll.get(50) == o);
    assertTrue("Failed to fix up list after insert", ll.get(51) == objArray[50] && (ll.get(52) == objArray[51]));
    ll.add(50, null);
    assertNull("Did not add null correctly", ll.get(50));
    try {
        ll.add(-1, "Test");
        fail("Should throw IndexOutOfBoundsException");
    } catch (IndexOutOfBoundsException e) {
    }
    try {
        ll.add(-1, null);
        fail("Should throw IndexOutOfBoundsException");
    } catch (IndexOutOfBoundsException e) {
    }
    try {
        ll.add(ll.size() + 1, "Test");
        fail("Should throw IndexOutOfBoundsException");
    } catch (IndexOutOfBoundsException e) {
    }
    try {
        ll.add(ll.size() + 1, null);
        fail("Should throw IndexOutOfBoundsException");
    } catch (IndexOutOfBoundsException e) {
    }
}
Example 2
Project: sosies-generator-master  File: QueueUtilsTest.java View source code
@org.junit.Test(timeout = 1000)
public void testUnmodifiableQueue() {
    fr.inria.diversify.testamplification.logger.Logger.writeTestStart(Thread.currentThread(), this, "testUnmodifiableQueue");
    Queue<java.lang.Object> queue = org.apache.commons.collections4.QueueUtils.unmodifiableQueue(new java.util.LinkedList<java.lang.Object>());
    fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(), 8161, (queue instanceof org.apache.commons.collections4.queue.UnmodifiableQueue));
    try {
        org.apache.commons.collections4.QueueUtils.unmodifiableQueue(null);
        org.apache.commons.collections4.QueueUtils.unmodifiableQueue(null);
    } catch (final IllegalArgumentException ex) {
    }
    fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(), 8162, queue);
    fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(), 8164, null, 8163, org.apache.commons.collections4.QueueUtils.unmodifiableQueue(queue));
    fr.inria.diversify.testamplification.logger.Logger.writeTestFinish(Thread.currentThread());
}
Example 3
Project: VaadinUtils-master  File: ExtensionsRegistryFactory.java View source code
@Override
public ExtensionsRegistry createRegistry(String registryId, JRPropertiesMap properties) {
    // TODO Auto-generated method stub
    return new ExtensionsRegistry() {

        @SuppressWarnings("unchecked")
        @Override
        public <T> List<T> getExtensions(Class<T> extensionType) {
            if (extensionType == net.sf.jasperreports.engine.export.JRHyperlinkProducerFactory.class) {
                List<T> list = new LinkedList<T>();
                list.add((T) new CustomJRHyperlinkProducerFactory());
                return list;
            }
            return new LinkedList<T>();
        }
    };
}
Example 4
Project: solmix-master  File: SpringContainerFactoryTest.java View source code
@Test
public void test() {
    SpringContainerFactory ssc = new SpringContainerFactory();
    Container sc = ssc.createContainer();
    ConfiguredBeanProvider provider = sc.getExtension(ConfiguredBeanProvider.class);
    List<?> l = provider.getBeanOfType("java.util.LinkedList", List.class);
    Assert.assertNotNull(l);
    ExtensionManager em = sc.getExtension(ExtensionManager.class);
    Assert.assertNotNull(em);
    Assert.assertNotNull(sc);
    Assert.assertNotNull("adaptermanager must be not ull", sc.getExtension(org.solmix.runtime.adapter.AdapterManager.class));
}
Example 5
Project: OrganicBuilder-master  File: InsertAtomValidator.java View source code
@Override
public String evaluate(final Collection<? extends Atom> atoms, final LevelMessages messages) {
    final LinkedList<Atom> joined = new LinkedList<Atom>();
    chainStart.getAllConnectedAtoms(joined);
    if (joined.size() != 11) {
        return messages.getError(1);
    }
    final int n_bonds[] = { 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1 };
    final AtomType types[] = { BasicType.E, BasicType.E, BasicType.E, BasicType.E, BasicType.E, BasicType.B, BasicType.E, BasicType.E, BasicType.E, BasicType.E, BasicType.E };
    int i = 0;
    final Iterator<Atom> it = joined.iterator();
    while (it.hasNext()) {
        final Atom a = it.next();
        if (a.getBonds().size() != n_bonds[i]) {
            return messages.getError(2);
        }
        if (a.getType() != types[i]) {
            return messages.getError(3);
        }
        i++;
    }
    return null;
}
Example 6
Project: ilarkesto-master  File: LongestCommonSubsequenceList2.java View source code
public static List<String> executeRecursive(List<String> a, List<String> b) {
    int aLen = a.size();
    int bLen = b.size();
    if (aLen == 0 || bLen == 0) {
        return new ArrayList<String>();
    } else if (a.get(aLen - 1).equals(b.get(bLen - 1))) {
        LinkedList<String> newList = new LinkedList<String>(b.subList(0, bLen - 1));
        newList.add(a.get(aLen - 1));
        return executeRecursive(a.subList(0, aLen - 1), newList);
    } else {
        List<String> x = executeRecursive(a, b.subList(0, bLen - 1));
        List<String> y = executeRecursive(a.subList(0, aLen - 1), b);
        return (x.size() > y.size()) ? x : y;
    }
}
Example 7
Project: Katari-master  File: LoginWithCaptchaControllerTest.java View source code
public final void testHandleRequestInternal_buttons() throws Exception {
    HttpServletRequest request;
    request = createMock(HttpServletRequest.class);
    expect(request.getMethod()).andReturn("GET");
    expect(request.getCharacterEncoding()).andReturn("UTF-8").anyTimes();
    replay(request);
    HttpServletResponse response;
    response = createMock(HttpServletResponse.class);
    List<String> buttons = new LinkedList<String>();
    buttons.add("b | a.do");
    LoginWithCaptchaController controller;
    controller = new LoginWithCaptchaController(true, buttons);
    ModelAndView mav = controller.handleRequestInternal(request, response);
    assertNotNull(mav);
    assertEquals("localLoginView", mav.getViewName());
    assertEquals(true, mav.getModel().get("showCaptcha"));
    assertEquals(buttons, mav.getModel().get("additionalButtons"));
}
Example 8
Project: clinic-softacad-master  File: SingleLineSqlCommandExtractor.java View source code
@Override
public String[] extractCommands(Reader reader) {
    BufferedReader bufferedReader = new BufferedReader(reader);
    List<String> statementList = new LinkedList<String>();
    try {
        for (String sql = bufferedReader.readLine(); sql != null; sql = bufferedReader.readLine()) {
            String trimmedSql = sql.trim();
            if (StringHelper.isEmpty(trimmedSql) || isComment(trimmedSql)) {
                continue;
            }
            if (trimmedSql.endsWith(";")) {
                trimmedSql = trimmedSql.substring(0, trimmedSql.length() - 1);
            }
            statementList.add(trimmedSql);
        }
        return statementList.toArray(new String[statementList.size()]);
    } catch (IOException e) {
        throw new ImportScriptException("Error during import script parsing.", e);
    }
}
Example 9
Project: katharsis-core-master  File: RequestBodyDeserializer.java View source code
@Override
public RequestBody deserialize(JsonParser jp, DeserializationContext deserializationContext) throws IOException {
    JsonNode node = jp.readValueAsTree();
    if (node == null) {
        return null;
    }
    RequestBody requestBody = new RequestBody();
    JsonNode data = node.get("data");
    Object value;
    if (data != null) {
        if (data.isArray()) {
            Iterator<JsonNode> nodeIterator = data.iterator();
            List<DataBody> dataBodies = new LinkedList<>();
            while (nodeIterator.hasNext()) {
                DataBody newLinkage = jp.getCodec().treeToValue(nodeIterator.next(), DataBody.class);
                dataBodies.add(newLinkage);
            }
            value = dataBodies;
        } else if (data.isObject()) {
            value = jp.getCodec().treeToValue(data, DataBody.class);
        } else if (data.isNull()) {
            value = null;
        } else {
            throw new RuntimeException("data field has wrong type: " + data.toString());
        }
        requestBody.setData(value);
    }
    return requestBody;
}
Example 10
Project: MUtils-master  File: ThreadUtil.java View source code
/**
     * Get threads for group
     */
public static Thread[] getGroup(String name) {
    Thread[] activeThreads = new Thread[Thread.activeCount()];
    int enumCount = Thread.enumerate(activeThreads);
    LinkedList<Thread> group = new LinkedList<Thread>();
    for (int i = 0; i < enumCount; i++) {
        Thread t = activeThreads[i];
        ThreadGroup tGroup = t.getThreadGroup();
        if (tGroup == null) {
            continue;
        }
        String gName = tGroup.getName();
        if (gName != null && gName.equals(name)) {
            group.add(t);
        }
    }
    Arrays.fill(activeThreads, null);
    Thread[] groupThreads = new Thread[group.size()];
    group.toArray(groupThreads);
    group.clear();
    return groupThreads;
}
Example 11
Project: jade_agents-master  File: LinkedList.java View source code
/**
     * @see jade.util.leap.Collection interface
     */
public Iterator iterator() {
    return new Iterator() {

        java.util.Iterator it = LinkedList.this.realHiddenList.iterator();

        /**
             * Method declaration
             * 
             * @return
             * 
             * @see
             */
        public boolean hasNext() {
            return it.hasNext();
        }

        /**
             * Method declaration
             * 
             * @return
             * 
             * @see
             */
        public Object next() {
            return it.next();
        }

        /**
             * Method declaration
             * 
             * @see
             */
        public void remove() {
            it.remove();
        }
    };
}
Example 12
Project: eclipselink.runtime-master  File: XmlValueCdnPricesTestCases.java View source code
public void testContainerType() {
    XMLDescriptor xDesc = xmlContext.getDescriptor(new QName("canadian-price"));
    assertNotNull("No descriptor was generated for CDNPricesNoAnnotation.", xDesc);
    DatabaseMapping mapping = xDesc.getMappingForAttributeName("prices");
    assertNotNull("No mapping exists on CDNPricesNoAnnotation for attribute [prices].", mapping);
    assertTrue("Expected an XMLCompositeDirectCollectionMapping for attribute [prices], but was [" + mapping.toString() + "].", mapping instanceof XMLCompositeDirectCollectionMapping);
    assertTrue("Expected container class [java.util.LinkedList] but was [" + ((XMLCompositeDirectCollectionMapping) mapping).getContainerPolicy().getContainerClassName() + "]", ((XMLCompositeDirectCollectionMapping) mapping).getContainerPolicy().getContainerClassName().equals("java.util.LinkedList"));
}
Example 13
Project: WaveInCloud-master  File: FastQueueGwtTest.java View source code
public void testQueue() throws Exception {
    final int TEST_ITERS = 500;
    int nextInt = 0;
    Random random = new Random(1);
    Queue<Integer> queue = new FastQueue<Integer>();
    Queue<Integer> reference = new LinkedList<Integer>();
    for (int i = 0; i < TEST_ITERS; i++) {
        if (random.nextBoolean()) {
            // enqueue test
            Integer value = random.nextDouble() < 0.9 ? nextInt++ : null;
            queue.offer(value);
            reference.offer(value);
            assertEquals(reference.size(), queue.size());
        } else {
            // dequeue test
            Integer actual = queue.poll();
            Integer expected = reference.poll();
            assertEquals(expected, actual);
            assertEquals(reference.size(), queue.size());
        }
    }
    // try the rest
    while (!reference.isEmpty()) {
        Integer actual = queue.poll();
        Integer expected = reference.poll();
        assertEquals(expected, actual);
        assertEquals(reference.size(), queue.size());
    }
}
Example 14
Project: nicehair-master  File: FindHairParser.java View source code
@Override
public JsonResult parse(String json) throws JSONException {
    // TODO Auto-generated method stub
    HairResult result = new HairResult();
    LinkedList<FindHairItem> mListInfo = new LinkedList<FindHairItem>();
    if (!TextUtils.isEmpty(json)) {
        result.setSuccess(true);
        JSONObject newsObject = new JSONObject(json);
        JSONObject jsonObject = newsObject.getJSONObject("data");
        JSONArray blogsJson = jsonObject.getJSONArray("blogs");
        for (int i = 0; i < blogsJson.length(); i++) {
            JSONObject jsonObj = blogsJson.getJSONObject(i);
            FindHairItem info = new FindHairItem();
            info.setHid(jsonObj.optString("albid"));
            info.setPicUrl(jsonObj.optString("isrc"));
            info.setTitle(jsonObj.optString("msg"));
            info.setPariseCount(jsonObj.optInt("favc"));
            info.setLookCount(jsonObj.optInt("iht"));
            info.setName(jsonObj.optString("unm"));
            info.setHeadUrl(jsonObj.optString("ava"));
            info.setLevel(10);
            //info.setHeight(jsonObj.optInt("iht"));
            mListInfo.add(info);
        }
    }
    result.setmListInfo(mListInfo);
    return result;
}
Example 15
Project: GeoGig-master  File: RebuildGraphOp.java View source code
/**
     * Executes the [email protected] RebuildGraphOp} operation.
     * 
     * @return a list of [email protected] ObjectId}s that were found to be missing or incomplete
     */
@Override
protected ImmutableList<ObjectId> _call() {
    Repository repository = repository();
    Preconditions.checkState(!repository.isSparse(), "Cannot rebuild the graph of a sparse repository.");
    List<ObjectId> updated = new LinkedList<ObjectId>();
    ImmutableList<Ref> branches = command(BranchListOp.class).setLocal(true).setRemotes(true).call();
    GraphDatabase graphDb = repository.graphDatabase();
    for (Ref ref : branches) {
        Iterator<RevCommit> commits = command(LogOp.class).setUntil(ref.getObjectId()).call();
        while (commits.hasNext()) {
            RevCommit next = commits.next();
            if (graphDb.put(next.getId(), next.getParentIds())) {
                updated.add(next.getId());
            }
        }
    }
    return ImmutableList.copyOf(updated);
}
Example 16
Project: octarine-master  File: RecordRowMapper.java View source code
@Override
default Record map(ResultSet resultSet) {
    List<Value> columnValues = new LinkedList<>();
    configure(new ColumnMappings() {

        private int index = 1;

        @Override
        public <T> ColumnMappings add(Key<? super T> key, String columnName, ColumnMapper<? extends T> columnMapper) {
            Optional<T> maybeColumnValue = Optional.ofNullable(columnMapper.apply(resultSet, index));
            index += 1;
            maybeColumnValue.ifPresent( columnValue -> columnValues.add(key.of(columnValue)));
            return this;
        }
    });
    return Record.of(columnValues);
}
Example 17
Project: teiid-designer-master  File: CompositeModelGenerator.java View source code
/**
     * @see org.teiid.designer.compare.generator.AbstractModelGenerator#doGenerateOutput(org.eclipse.core.runtime.IProgressMonitor, java.util.LinkedList)
     */
@Override
protected void doGenerateOutput(final IProgressMonitor monitor, final LinkedList problems) throws UserCancelledException {
    // Generate all of the contained ...
    final Iterator iter = getModelGenerators().iterator();
    while (iter.hasNext()) {
        final ModelGenerator generator = (ModelGenerator) iter.next();
        final IStatus status = generator.generateOutput(monitor);
        problems.add(status);
    }
}
Example 18
Project: java-promises-master  File: FooTestCase.java View source code
@Test
public void testFoo() {
    Deferred<Integer> d = new Deferred<Integer>();
    final Deferred<String> d2 = new Deferred<String>();
    Promise<String> p = d.promise.then(new PromisingCallback<Integer, String>() {

        public Promise<String> call(Integer arg) throws Exception {
            return d2.promise;
        }
    });
    LinkedList<String> done = new LinkedList<String>();
    p.then(Callbacks.addToHandler(done));
    d.resolve(4);
    System.out.println("done = " + done);
    d2.resolve("foo");
    System.out.println("done = " + done);
}
Example 19
Project: breakout-master  File: TaskServiceSubtaskFilePersister.java View source code
@Override
protected void saveInBackground(final LinkedList<M> batch) {
    Task task = new Task(description) {

        @Override
        protected void execute() throws Exception {
            try {
                save(batch.getLast(), this);
            } finally {
                TaskServiceSubtaskFilePersister.this.batcher.doneHandling(batch);
            }
        }
    };
    task.setTotal(1000);
    service.submit(task);
}
Example 20
Project: dataverse-master  File: ListDataverseContentCommand.java View source code
@Override
public List<DvObject> execute(CommandContext ctxt) throws CommandException {
    LinkedList<DvObject> result = new LinkedList<>();
    for (Dataset ds : ctxt.datasets().findByOwnerId(dvToList.getId())) {
        try {
            ds = ctxt.engine().submit(new GetDatasetCommand(getRequest(), ds));
            result.add(ds);
        } catch (PermissionException ex) {
        }
    }
    for (Dataverse dv : ctxt.dataverses().findByOwnerId(dvToList.getId())) {
        try {
            dv = ctxt.engine().submit(new GetDataverseCommand(getRequest(), dv));
            result.add(dv);
        } catch (PermissionException ex) {
        }
    }
    return result;
}
Example 21
Project: erlide-master  File: CommandData.java View source code
// non-interactive
public void addUserInput(final List<String> input) {
    final List<OtpErlangObject> argsTmp = new LinkedList<>();
    final OtpErlangObject[] userInput = new OtpErlangObject[input.size()];
    int i = 0;
    for (final String text : input) {
        userInput[i] = new OtpErlangString(text);
        i++;
    }
    for (final OtpErlangObject arg : args) {
        if (arg instanceof OtpErlangTuple && ((OtpErlangTuple) arg).elementAt(0).equals(new OtpErlangAtom("prompt"))) {
            argsTmp.add(new OtpErlangList(userInput));
        // TODO make it so that it adds input only once, check repeat
        // interactive
        } else {
            argsTmp.add(arg);
        }
    }
    args = argsTmp.toArray(new OtpErlangObject[0]);
}
Example 22
Project: bixie-master  File: JavaFalsePositives.java View source code
@Parameterized.Parameters(name = "{index}: check ({1})")
public static Collection<Object[]> data() {
    List<Object[]> filenames = new LinkedList<Object[]>();
    final File source_dir = new File(testRoot + "ic_java/false_positives/");
    File[] directoryListing = source_dir.listFiles();
    if (directoryListing != null) {
        for (File child : directoryListing) {
            if (child.isFile() && child.getName().endsWith(".java")) {
                filenames.add(new Object[] { child, child.getName() });
            } else {
            //Ignore
            }
        }
    } else {
        // directories.
        throw new RuntimeException("Test data not found!");
    }
    return filenames;
}
Example 23
Project: wso2-synapse-master  File: EndDelimitedProtocolTest.java View source code
public void test() throws IOException {
    byte delimiter = 0;
    Random random = new Random();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    List<byte[]> messages = new LinkedList<byte[]>();
    for (int i = 0; i < 20; i++) {
        int size = 64 + random.nextInt(2048);
        byte[] data = new byte[size];
        for (int j = 0; j < size; j++) {
            data[j] = (byte) (32 + random.nextInt(96));
        }
        out.write(data);
        out.write(delimiter);
        messages.add(data);
    }
    EndDelimitedProtocol protocol = new EndDelimitedProtocol();
    protocol.setDelimiter(delimiter);
    ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
    ProtocolDecoder decoder = protocol.createProtocolDecoder();
    byte[] readBuffer = new byte[1024];
    while (true) {
        int remaining = messages.size();
        while (decoder.inputRequired()) {
            int c = in.read(readBuffer);
            if (c == -1) {
                assertTrue("Expected " + remaining + " more messages", remaining == 0);
                return;
            }
            decoder.decode(readBuffer, 0, c);
        }
        assertTrue("Didn't expecte any more messages", remaining != 0);
        byte[] actual = decoder.getNext();
        byte[] expected = messages.remove(0);
        assertEquals(new String(expected, "us-ascii"), new String(actual, "us-ascii"));
    }
}
Example 24
Project: streamex-master  File: InternalsTest.java View source code
@Test
public void testArrayCollection() {
    Collection<Object> collection = new ArrayCollection(new Object[] { "1", "2" });
    List<Object> list = new LinkedList<>(collection);
    assertEquals("1", list.get(0));
    assertEquals("2", list.get(1));
    List<Object> list2 = new ArrayList<>(collection);
    assertEquals("1", list.get(0));
    assertEquals("2", list.get(1));
    assertEquals(list2, list);
    Set<Object> set = new HashSet<>(collection);
    assertTrue(set.contains("1"));
    assertTrue(set.contains("2"));
    assertEquals(2, set.size());
}
Example 25
Project: cloudtm-data-platform-master  File: CreateThousandCachesTest.java View source code
public void doTest() throws Exception {
    System.out.println("Starting... ");
    withCacheManager(new CacheManagerCallable(new DefaultCacheManager()) {

        @Override
        public void call() throws Exception {
            List<Cache<?, ?>> thousandCaches = new LinkedList<Cache<?, ?>>();
            long start = System.currentTimeMillis();
            for (int i = 0; i < 1000; i++) {
                thousandCaches.add(cm.getCache("cache" + i));
            }
            System.out.println("Created 1000 basic caches in " + (System.currentTimeMillis() - start) + " millis");
        }
    });
}
Example 26
Project: cdo-master  File: DB4OLockEntry.java View source code
public static List<DB4OLockEntry> getPrimitiveLockEntries(DB4OLockArea primitive, Map<CDOID, LockGrade> locks) {
    List<DB4OLockEntry> newList = new LinkedList<DB4OLockEntry>();
    for (Entry<CDOID, LockGrade> entry : locks.entrySet()) {
        CDOID cdoid = entry.getKey();
        long longCdoID = CDOIDUtil.getLong(cdoid);
        LockGrade lockGrade = entry.getValue();
        int intLockGrade = lockGrade.getValue();
        DB4OLockEntry lockEntry = getEntry(primitive.getLockEntries(), longCdoID);
        if (lockEntry == null) {
            lockEntry = new DB4OLockEntry(longCdoID, intLockGrade);
        } else {
            lockEntry.setLockGrade(intLockGrade);
        }
        newList.add(lockEntry);
    }
    return newList;
}
Example 27
Project: google-web-toolkit-svnmirror-master  File: ReflectionUtils.java View source code
public static <A extends Annotation> A getAnnotation(Class<?> clazz, Class<A> annotClass, boolean forceInherit) {
    boolean inherited = forceInherit || annotClass.isAnnotationPresent(Inherited.class);
    LinkedList<Class<?>> workQueue = new LinkedList<Class<?>>();
    workQueue.add(clazz);
    while (!workQueue.isEmpty()) {
        clazz = workQueue.removeFirst();
        A result = clazz.getAnnotation(annotClass);
        if (result != null || !inherited) {
            return result;
        }
        Class<?> superClass = clazz.getSuperclass();
        if (superClass != null) {
            workQueue.addLast(superClass);
        }
        workQueue.addAll(Arrays.asList((Class<?>[]) clazz.getInterfaces()));
    }
    return null;
}
Example 28
Project: keycloak-master  File: MigrateTo2_3_0.java View source code
private void updateProtocolMappers(ProtocolMapperContainerModel client) {
    List<ProtocolMapperModel> toUpdate = new LinkedList<>();
    for (ProtocolMapperModel mapper : client.getProtocolMappers()) {
        if (!mapper.getConfig().containsKey("userinfo.token.claim") && mapper.getConfig().containsKey("id.token.claim")) {
            mapper.getConfig().put("userinfo.token.claim", mapper.getConfig().get("id.token.claim"));
            toUpdate.add(mapper);
        }
    }
    for (ProtocolMapperModel mapper : toUpdate) {
        client.updateProtocolMapper(mapper);
    }
}
Example 29
Project: dashbuilder-master  File: DataSelectionEvent.java View source code
public static void fire(HasDataSelectionEventHandlers source, Object sender, JavaScriptObject data) {
    DataSelectionEvent event = new DataSelectionEvent(sender);
    JSONObject array = new JSONObject(data);
    event.series = new LinkedList<Series>();
    for (String key : array.keySet()) {
        JSONObject obj = array.get(key).isObject();
        if (obj != null) {
            Series series1 = JavaScriptObject.createObject().cast();
            series1.setValue(obj.get("value").isNumber().doubleValue());
            series1.setColor(obj.get("fillColor").isString().stringValue());
            event.series.add(series1);
        }
    }
    source.fireEvent(event);
}
Example 30
Project: org.eclipse.ecr-master  File: SaveOptionsDescriptor.java View source code
public List<VersioningOption> getVersioningOptionList() {
    List<VersioningOption> opts = new LinkedList<VersioningOption>();
    if (none != null) {
        if (none.isDefault()) {
            opts.add(0, NONE);
        } else {
            opts.add(NONE);
        }
    }
    if (minor != null) {
        if (minor.isDefault()) {
            opts.add(0, MINOR);
        } else {
            opts.add(MINOR);
        }
    }
    if (major != null) {
        if (major.isDefault()) {
            opts.add(0, MAJOR);
        } else {
            opts.add(MAJOR);
        }
    }
    return opts;
}
Example 31
Project: GlowstonePlusPlus-master  File: GlowCreature.java View source code
@Override
public List<Message> createSpawnMessage() {
    List<Message> result = new LinkedList<>();
    // spawn mob
    int x = Position.getIntX(location);
    int y = Position.getIntY(location);
    int z = Position.getIntZ(location);
    int yaw = Position.getIntYaw(location);
    int pitch = Position.getIntPitch(location);
    result.add(new SpawnMobMessage(id, type.getTypeId(), x, y, z, yaw, pitch, pitch, 0, 0, 0, metadata.getEntryList()));
    // head facing
    result.add(new EntityHeadRotationMessage(id, yaw));
    //result.add(createEquipmentMessage());
    return result;
}
Example 32
Project: cdt-tests-runner-master  File: MIRegistersTest_7_2.java View source code
// GDB's list of registers is different with GDB 7.2
@Override
protected List<String> get_X86_REGS() {
    List<String> list = new LinkedList<String>(Arrays.asList("eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi", "eip", "eflags", "cs", "ss", "ds", "es", "fs", "gs", "st0", "st1", "st2", "st3", "st4", "st5", "st6", "st7", "fctrl", "fstat", "ftag", "fiseg", "fioff", "foseg", "fooff", "fop", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7", /*"","","","","","","","",*/
    "mxcsr", "orig_eax", "al", "cl", "dl", "bl", "ah", "ch", "dh", "bh", "ax", "cx", /*"",*/
    "dx", "bx", "bp", "si", "di", "mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7"));
    // On Windows, gdb doesn't report "orig_eax" as a register. Apparently it does on Linux
    if (Platform.getOS().equals(Platform.OS_WIN32)) {
        list.remove("orig_eax");
    }
    return list;
}
Example 33
Project: dcache-master  File: SourceBackedPredicateMap.java View source code
/**
     * Get values from the map belonging to a specific key
     * @param key Key to be used to find corresponding values
     * @return Collection of matching values
     */
public synchronized List<TValue> getValuesForPredicatesMatching(TKey key) {
    if (_source.hasChanged()) {
        try {
            _log.info("Source changed. Recreating map.");
            createMapFromData(_source.getContent());
        } catch (IOException e) {
            _log.error("Error creating map.", e);
            return Collections.emptyList();
        }
    }
    List<TValue> result = new LinkedList<>();
    for (Entry<MapPredicate<TKey>, TValue> predicateEntry : _predicateValueMap.entrySet()) {
        if (predicateEntry.getKey().matches(key)) {
            result.add(predicateEntry.getValue());
        }
    }
    return result;
}
Example 34
Project: xchain-master  File: TestValidate3.java View source code
public boolean execute(JXPathContext context) throws Exception {
    Session session = HibernateLifecycle.getCurrentSession(getName(context));
    Map contextHolder = new HashMap();
    List beans = new LinkedList();
    Person bean1 = new Person();
    beans.add(bean1);
    Person bean2 = new Person();
    beans.add(bean2);
    Person bean3 = new Person();
    bean3.setId(new Integer(1234));
    bean3.setName("Test Person");
    beans.add(bean3);
    contextHolder.put("beans", beans);
    context.getVariables().declareVariable("test-validate-beans", contextHolder);
    // execute the chain 
    return super.execute(context);
}
Example 35
Project: eis-master  File: AllPerceptPerceptHandler.java View source code
@Override
public final LinkedList<Percept> getAllPercepts() throws PerceiveException {
    LinkedList<Percept> percepts = new LinkedList<Percept>();
    Map<Method, Object> batchPerceptObjects;
    batchPerceptObjects = allPercepProvider.getAllPercepts();
    for (Entry<Method, Object> entry : batchPerceptObjects.entrySet()) {
        Method method = (Method) entry.getKey();
        Object perceptObject = entry.getValue();
        List<Object> perceptObjects = unpackPerceptObject(method, perceptObject);
        List<Percept> translatedPercepts = translatePercepts(method, perceptObjects);
        percepts.addAll(translatedPercepts);
    }
    return percepts;
}
Example 36
Project: android-essentials-toolbox-master  File: Example3.java View source code
/**
	 * List the permissions requested in the manifest that are used by the app
	 * @param projectName An Eclipse project name of an Android application in the workspace to analyze
	 * @return A collection of used Permission objects
	 * @throws Exception Exception in the event that AndroidManifest.xml files is missing or corrupt
	 */
public static Collection<Permission> getUsedPermissions(String projectName) throws Exception {
    // parse the manifest for the target sdk version and the requested permissions
    AndroidManifest manifest = new AndroidManifest(AndroidManifest.getManifestFile(projectName));
    int targetSDKVersion = manifest.getTargetSDKVersion();
    Collection<Permission> requestedPermissions = manifest.getUsesPermissions();
    // create a collection of unused permissions
    Collection<Permission> usedPermissions = new LinkedList<Permission>();
    for (Permission permission : requestedPermissions) {
        if (Example1.isPermissionUsed(permission, targetSDKVersion)) {
            usedPermissions.add(permission);
        }
    }
    return usedPermissions;
}
Example 37
Project: schach-master  File: Fingerprint.java View source code
/*
     * Gibt einen eindeutigen Fingerprint des aktuellen Spielfeldes
     * (Schachfiguren auf Brett) zurueck, um eine Situation zu identifizieren
     * 
     * @param map HashMap<Integer,Byte> mit Situation von der Fingerprint
     * erstellt werden soll
     * 
     * @return String Fingerprint als String als Format
     * "pos1,figwert1--pos2,figwert2--..."
     */
@SuppressWarnings("unchecked")
public static String getFingerprint(HashMap<Integer, Byte> map) {
    HashMap<Integer, Byte> cloneMap = (HashMap<Integer, Byte>) map.clone();
    String fingerprint = "";
    Iterator<Entry<Integer, Byte>> it = cloneMap.entrySet().iterator();
    /*
         * Da die HashMap die Eintraege unterschiedlich ausliest, ist hier die Moeglichkeit,
         * FigureValue mit position zu verknuepfen um sie dann sortieren zu koennen.
         */
    class Identifier implements Comparable {

        byte figureValue;

        int position;

        public Identifier(byte figureValue, int position) {
            this.figureValue = figureValue;
            this.position = position;
        }

        public byte getFigureValue() {
            return this.figureValue;
        }

        public int getPosition() {
            return this.position;
        }

        public int compareTo(Object id) {
            int position;
            if (id instanceof Identifier) {
                position = ((Identifier) id).getPosition();
                return (position - this.position);
            } else {
                return 0;
            }
        }
    }
    List<Identifier> id = new LinkedList<Identifier>();
    while (it.hasNext()) {
        Map.Entry<Integer, Byte> pair = (Map.Entry<Integer, Byte>) it.next();
        byte figureValue = pair.getValue();
        int position = pair.getKey().intValue();
        id.add(new Identifier(figureValue, position));
        it.remove();
    }
    //fuer einen eindeutigen Fingerprint, muss Liste sortiert werden.
    Collections.sort(id);
    while (id.size() > 0) {
        fingerprint += id.get(0).getPosition() + "," + id.get(0).getFigureValue() + "--";
        id.remove(0);
    }
    fingerprint = fingerprint.substring(0, fingerprint.length() - 2);
    return fingerprint;
}
Example 38
Project: picard-tools-master  File: PerTileFileUtil.java View source code
@Override
public List<String> fakeFiles(final List<Integer> expectedTiles, final int[] cycles, final IlluminaFileUtil.SupportedIlluminaFormat format) {
    final List<String> failures = new LinkedList<String>();
    if (!base.exists()) {
        failures.add("Base directory(" + base.getAbsolutePath() + ") does not exist!");
    } else {
        for (final Integer tile : expectedTiles) {
            if (!tiles.contains(tile) || fileMap.get(tile).length() == 0) {
                //create a new file of this type
                try {
                    faker.fakeFile(base, tile, lane, extension);
                } catch (final IOException e) {
                    failures.add(String.format("Could not create fake file %s: %s", fileMap.get(tile), e.getMessage()));
                }
            }
        }
    }
    return failures;
}
Example 39
Project: tmdm-studio-se-master  File: OpenMarkerHandlerRegister.java View source code
public static List<IOpenMarkerHandler> getHandlers() {
    if (handlers == null) {
        handlers = new LinkedList<IOpenMarkerHandler>();
        IExtensionRegistry registry = Platform.getExtensionRegistry();
        //
        IExtensionPoint extensionPoint = registry.getExtensionPoint(ValidatePlugin.PLUGIN_ID, EXTENSION_POINT_TEMPLATE);
        if (extensionPoint != null && extensionPoint.isValid()) {
            IExtension[] extensions = extensionPoint.getExtensions();
            for (IExtension s : extensions) {
                IConfigurationElement[] elements = s.getConfigurationElements();
                for (IConfigurationElement element : elements) {
                    if (element.getAttribute(PROP_CLASS) != null) {
                        try {
                            IOpenMarkerHandler handler = (IOpenMarkerHandler) element.createExecutableExtension(PROP_CLASS);
                            handlers.add(handler);
                        } catch (CoreException e) {
                            log.error(e.getMessage(), e);
                        }
                    }
                }
            }
        }
    }
    return handlers;
}
Example 40
Project: cdt-master  File: ResourceExclusion.java View source code
@Override
public synchronized boolean testExclusion(IResource resource) {
    // Populate the resources to be excluded by this exclusion.
    List<IResource> excludedResources = new LinkedList<IResource>();
    List<ExclusionInstance> exclusionInstances = getExclusionInstances();
    for (ExclusionInstance instance : exclusionInstances) {
        excludedResources.add(instance.getResource());
    }
    if (excludedResources.contains(resource)) {
        return true;
    }
    // Check to see if the given resource is part of this exclusion.
    for (IResource excludedResource : excludedResources) {
        // TODO: need to update this for Phase 2 implementation
        if (excludedResource instanceof IContainer) {
            IContainer container = (IContainer) excludedResource;
            if (container.getFullPath().isPrefixOf(resource.getFullPath())) {
                return true;
            }
        }
    }
    return false;
}
Example 41
Project: aws-toolkit-eclipse-master  File: DeploymentsTableViewTreePathContentCache.java View source code
private Object[] loadChildren(TreePath parent) {
    if (parent.getSegmentCount() == 0) {
        // root
        List<DeploymentInfo> deployments = ServiceAPIUtils.getAllDeployments(editorInput.getCodeDeployClient(), editorInput.getApplicationName(), editorInput.getDeploymentGroupName());
        // Sort by creation data
        Collections.sort(deployments, new Comparator<DeploymentInfo>() {

            public int compare(DeploymentInfo a, DeploymentInfo b) {
                int a_to_b = a.getCreateTime().compareTo(b.getCreateTime());
                // In descending order
                return -a_to_b;
            }
        });
        return deployments.toArray(new DeploymentInfo[deployments.size()]);
    } else {
        Object lastSegment = parent.getLastSegment();
        if (lastSegment instanceof DeploymentInfo) {
            DeploymentInfo deployment = (DeploymentInfo) lastSegment;
            List<InstanceSummary> instances = ServiceAPIUtils.getAllDeploymentInstances(editorInput.getCodeDeployClient(), deployment.getDeploymentId());
            return instances.toArray(new InstanceSummary[instances.size()]);
        } else if (lastSegment instanceof InstanceSummary) {
            InstanceSummary deploymentInstance = (InstanceSummary) lastSegment;
            List<LifecycleEvent> events = deploymentInstance.getLifecycleEvents();
            if (events == null) {
                events = new LinkedList<LifecycleEvent>();
            }
            return events.toArray(new LifecycleEvent[events.size()]);
        }
    }
    return new Object[0];
}
Example 42
Project: android-bankdroid-master  File: LegacyProviderConfiguration.java View source code
private List<Field> createConfiguration() {
    List<Field> configuration = new LinkedList<>();
    configuration.add(new FieldBuilder(USERNAME).label(mLegacyBank.getContext().getString(mLegacyBank.getInputTitleUsername())).placeholder(mLegacyBank.getInputHintUsername()).hidden(mLegacyBank.isInputUsernameHidden()).required(true).fieldType(FieldTypeMapper.toFieldType(mLegacyBank.getInputTypeUsername())).build());
    configuration.add(new FieldBuilder(PASSWORD).label(mLegacyBank.getContext().getString(mLegacyBank.getInputTitlePassword())).hidden(mLegacyBank.isInputPasswordHidden()).secret(true).required(!mLegacyBank.isInputPasswordHidden()).fieldType(FieldTypeMapper.toFieldType(mLegacyBank.getInputTypePassword())).build());
    configuration.add(new FieldBuilder(EXTRAS).label(mLegacyBank.getContext().getString(mLegacyBank.getInputTitleExtras())).hidden(mLegacyBank.isInputExtrasHidden()).fieldType(FieldTypeMapper.toFieldType(mLegacyBank.getInputTypeExtras())).build());
    return configuration;
}
Example 43
Project: galen-master  File: SpecTextProcessor.java View source code
@Override
public Spec process(StringCharReader reader, String contextPath) {
    /* first building up a list of text operations */
    List<String> textOperations = new LinkedList<>();
    SpecText.Type textCheckType = null;
    while (textCheckType == null && reader.hasMoreNormalSymbols()) {
        String word = reader.readWord();
        if (word.isEmpty()) {
            throw new SyntaxException("Expected text check type, but got nothing");
        }
        if (SpecText.Type.isValid(word)) {
            textCheckType = SpecText.Type.fromString(word);
        } else {
            textOperations.add(word);
        }
    }
    String expectedText = Expectations.doubleQuotedText().read(reader);
    if (reader.hasMoreNormalSymbols()) {
        throw new SyntaxException("Too many arguments for spec: " + reader.getTheRest().trim());
    }
    return new SpecText(textCheckType, expectedText, textOperations);
}
Example 44
Project: heron-master  File: AllGroupingTest.java View source code
/**
   * Method: getListToSend(HeronTuples.HeronDataTuple tuple)
   */
@Test
public void testGetListToSend() throws Exception {
    List<Integer> taskIds = new LinkedList<>();
    for (int i = 0; i < 100; ++i) {
        taskIds.add(i);
    }
    AllGrouping g = new AllGrouping(taskIds);
    for (int i = 0; i < 1000; ++i) {
        HeronTuples.HeronDataTuple dummy = HeronTuples.HeronDataTuple.getDefaultInstance();
        List<Integer> dest = g.getListToSend(dummy);
        Assert.assertEquals(dest.size(), taskIds.size());
        Collections.sort(dest);
        for (int j = 0; j < taskIds.size(); ++j) {
            Assert.assertEquals(taskIds.get(j), dest.get(j));
        }
    }
}
Example 45
Project: SideScrollerGDW2012-Max-master  File: WindowsIpaddressen.java View source code
private LinkedList<InetAddress> getSubnet() throws IOException {
    Process process = Runtime.getRuntime().exec("ipconfig");
    Scanner scanner = new Scanner(process.getInputStream());
    LinkedList<InetAddress> result = new LinkedList<InetAddress>();
    String line;
    //get Programmoutput
    while (scanner.hasNextLine()) {
        if ((line = scanner.nextLine()).contains("IPv4")) {
            String partResult = new String();
            //found input
            String ipAddress = line.split(":")[1];
            line = scanner.nextLine();
            String subnetMask = line.split(":")[1];
            ipAddress = ipAddress.trim();
            subnetMask = subnetMask.trim();
            //split into parts	
            String[] ipAddressParts = ipAddress.split("\\.");
            String[] subnetMaskParts = subnetMask.split("\\.");
            //parse...
            for (int i = 0; i < 4; ++i) {
                if (subnetMaskParts[i].equals("255")) //copy complete
                {
                    partResult += ipAddressParts[i] + ".";
                } else if (subnetMaskParts[i].equals("0")) //empty part
                {
                    partResult += "255.";
                } else //calc...
                {
                    short ipValue = Short.parseShort(ipAddressParts[i]);
                    short subValue = Short.parseShort(subnetMaskParts[i]);
                    subValue *= -1;
                    ipValue &= subValue;
                    partResult += Short.toString(ipValue) + ".";
                }
            }
            //debug
            String sringResult = partResult.substring(0, partResult.length() - 1);
            result.add(InetAddress.getByName(sringResult));
        }
    }
    return result;
}
Example 46
Project: powermock-master  File: PowerMockExpectedExceptionsExtractorImpl.java View source code
public String[] getPackagesToIgnore(AnnotatedElement element) {
    List<String> ignoredPackages = new LinkedList<String>();
    if (element instanceof Class<?>) {
        Class<?> klazz = (Class<?>) element;
        for (Method method : klazz.getMethods()) {
            Test annotation = method.getAnnotation(Test.class);
            if (annotation != null) {
                Class<?>[] ignores = annotation.expectedExceptions();
                if (ignores != null) {
                    for (Class<?> ignorePackage : ignores) {
                        ignoredPackages.add(ignorePackage.getName());
                    }
                }
            }
        }
        Class<?> superclass = klazz.getSuperclass();
        if (superclass != null && !superclass.equals(Object.class)) {
            String[] packagesToIgnore = getPackagesToIgnore(superclass);
            ignoredPackages.addAll(Arrays.asList(packagesToIgnore));
        }
    }
    return ignoredPackages.toArray(new String[ignoredPackages.size()]);
}
Example 47
Project: REST-OCD-Services-master  File: StringConverter.java View source code
public LinkedList<String> StringToList(String thread) {
    LinkedList<String> res = new LinkedList<String>();
    int begin = 0;
    int end = 0;
    String temp = null;
    boolean add;
    int len = thread.length();
    if (thread == null || thread.isEmpty()) {
        return null;
    }
    for (int i = 0; i < len; i++) {
        if (thread.charAt(i) != ' ') {
            begin = i;
            end = i;
            while (i < len && thread.charAt(i) != ' ') {
                end++;
                i++;
            }
            add = true;
            temp = thread.substring(begin, end);
            if (res.contains(temp)) {
                add = false;
            }
            /*for(Iterator<String> it = res.iterator(); it.hasNext();){
					if(temp.equals(it.next())){
						add = false;
					}
				}*/
            if (add) {
                res.add(temp);
            }
        }
    }
    return res;
}
Example 48
Project: many-ql-master  File: QuestionChecker.java View source code
public boolean duplicates(Node node) {
    LinkedList<? extends Node> nodes = node.getNodes();
    System.out.println(nodes.size());
    for (int i = 0; i < nodes.size(); i++) {
        if (nodes.get(i).getClass().equals(uva.TaxForm.AST.NodeQuestion.Question.class)) {
            System.out.println(nodes.get(i).toString());
            questions.add((Question<?>) nodes.get(i));
        } else {
            duplicates(nodes.get(i));
        }
    }
    if (questions.size() > 0) {
        duplicate = sameQuestion(questions);
    }
    return duplicate;
}
Example 49
Project: framework-master  File: BeanItemContainerTest.java View source code
/**
     * Test class for BeanItemContainer
     *
     * @throws IllegalAccessException
     * @throws InstantiationException
     */
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
    BeanItemContainer<Hello> c = new BeanItemContainer<>(Hello.class);
    c.addItem(new Hello());
    Collection<Hello> col = new LinkedList<>();
    for (int i = 0; i < 100; i++) {
        col.add(new Hello());
    }
    col.add(new Hello2());
    c = new BeanItemContainer<>(col);
    System.out.println(c + " contains " + c.size() + " objects");
    // test that subclass properties are handled correctly
    System.out.println(c + " item 0 second = " + c.getContainerProperty(c.getIdByIndex(0), "second"));
    System.out.println(c + " item 100 second = " + c.getContainerProperty(c.getIdByIndex(100), "second"));
}
Example 50
Project: TextSecureSMP-master  File: ListPartitionTest.java View source code
public void testPartitionEven() {
    List<Integer> list = new LinkedList<>();
    for (int i = 0; i < 100; i++) {
        list.add(i);
    }
    List<List<Integer>> partitions = Util.partition(list, 10);
    assertEquals(partitions.size(), 10);
    int counter = 0;
    for (int i = 0; i < partitions.size(); i++) {
        List<Integer> partition = partitions.get(i);
        assertEquals(partition.size(), 10);
        for (int j = 0; j < partition.size(); j++) {
            assertEquals((int) partition.get(j), counter++);
        }
    }
}
Example 51
Project: keratin-irc-master  File: ConnectionPreamble.java View source code
/**
     * Sends the two required NICK and USER messages in sequence immediately after a connection is made.
     */
@Handler(priority = Integer.MIN_VALUE + 1)
private void initialConnectionHandler(IrcConnect event) {
    OutputQueue replyQueue = event.getReplyQueue();
    Logger.trace("Sending connection nick/user preamble");
    try {
        List<IrcMessage> messageList = new LinkedList<IrcMessage>();
        // TODO use SendMessage's static methods
        messageList.add(SendMessage.nick(nick));
        messageList.add(SendMessage.user(user, "0", realName));
        for (IrcMessage message : messageList) replyQueue.offer(message);
    } catch (InvalidMessageParamException e) {
        Logger.error(e, "Couldn't enqueue nick/user info preamble.");
    }
}