Java Code Examples for java.util.Arrays.asList()

The following are Jave code examples for showing how to use asList() of the java.util.Arrays class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: athena   File: SimpleDeviceStoreTest.java   View Source Code Vote up 6 votes
@Test
public final void testUpdatePortStatus() {
    putDevice(DID1, SW1);
    List<PortDescription> pds = Arrays.<PortDescription>asList(
            new DefaultPortDescription(P1, true)
            );
    deviceStore.updatePorts(PID, DID1, pds);

    DeviceEvent event = deviceStore.updatePortStatus(PID, DID1,
            new DefaultPortDescription(P1, false));
    assertEquals(PORT_UPDATED, event.type());
    assertDevice(DID1, SW1, event.subject());
    assertEquals(P1, event.port().number());
    assertFalse("Port is disabled", event.port().isEnabled());

}
 
Example 2
Project: jwala   File: JvmCommandFactory.java   View Source Code Vote up 6 votes
/**
 * Method to generate remote command for installing service for jvm
 *
 * @param jvm
 * @return
 */
private ExecCommand getExecCommandForInstallService(Jvm jvm) {
    final String userName;
    final String encryptedPassword;

    if (jvm.getUserName() != null) {
        userName = jvm.getUserName();
        encryptedPassword = jvm.getEncryptedPassword();
    } else {
        userName = null;
        encryptedPassword = null;
    }

    final String quotedUsername = addQuotes(userName);
    final String decryptedPassword = encryptedPassword != null && encryptedPassword.length() > 0 ? new DecryptPassword().decrypt(encryptedPassword) : "";
    final String quotedPassword = addQuotes(decryptedPassword);

    List<String> formatStrings = Arrays.asList(getFullPathScript(jvm, INSTALL_SERVICE_SCRIPT_NAME.getValue()),
            jvm.getJvmName(), jvm.getTomcatMedia().getRemoteDir().normalize().toString(),
            jvm.getTomcatMedia().getRootDir().toString());
    List<String> unformatStrings = Arrays.asList(quotedUsername, quotedPassword);

    return new ExecCommand(formatStrings, unformatStrings);
}
 
Example 3
Project: groupsio-api-java   File: UserResource.java   View Source Code Vote up 6 votes
/**
 * Gets a list of {@link Subscription}s that the current user is subscribed
 * to.
 * 
 * @return {@link List}<{@link Subscription}> representing the subscriptions
 * @throws URISyntaxException
 * @throws IOException
 * @throws GroupsIOApiException
 */
public List<Subscription> getSubscriptions() throws URISyntaxException, IOException, GroupsIOApiException
{
    final URIBuilder uri = new URIBuilder().setPath(baseUrl + "getsubs");
    uri.setParameter("limit", MAX_RESULTS);
    final HttpGet request = new HttpGet();
    request.setURI(uri.build());
    
    Page page = callApi(request, Page.class);
    
    final List<Subscription> subscriptions = Arrays.asList(OM.convertValue(page.getData(), Subscription[].class));
    
    while (page.getHasMore())
    {
        uri.setParameter("page_token", page.getNextPageToken().toString());
        request.setURI(uri.build());
        page = callApi(request, Page.class);
        subscriptions.addAll(Arrays.asList(OM.convertValue(page.getData(), Subscription[].class)));
    }
    
    return subscriptions;
}
 
Example 4
Project: elements-of-programming-interviews-solutions   File: Rotate2DArrayTest.java   View Source Code Vote up 6 votes
@Test
public void rotateMatix1() {
    expected = Arrays.asList(
            Arrays.asList(13,9,5,1),
            Arrays.asList(14,10,6,2),
            Arrays.asList(15,11,7,3),
            Arrays.asList(16,12,8,4)
    );
    matrix = Arrays.asList(
            Arrays.asList(1,2,3,4),
            Arrays.asList(5,6,7,8),
            Arrays.asList(9,10,11,12),
            Arrays.asList(13,14,15,16)
    );

    test(expected, matrix);
}
 
Example 5
Project: genius-groupie   File: SectionTest.java   View Source Code Vote up 6 votes
@Test
public void insertGroupToNestedSectionNotifiesAtCorrectIndex() throws Exception {
    final Section rootSection = new Section();

    rootSection.setGroupDataObserver(groupAdapter);
    groupAdapter.add(rootSection);

    final Section nestedSection1 = new Section(Arrays.asList(new DummyItem(), new DummyItem()));
    rootSection.add(nestedSection1);

    final Section nestedSection2 = new Section(Arrays.asList(new DummyItem(), new DummyItem(), new DummyItem()));
    rootSection.add(nestedSection2);

    final Section nestedSection3 = new Section(Arrays.asList(new DummyItem(), new DummyItem()));

    reset(groupAdapter);
    rootSection.add(1, nestedSection3);
    verify(groupAdapter).onItemRangeInserted(rootSection, 2, 2);
}
 
Example 6
Project: Jupiter   File: SimpleCommandMap.java   View Source Code Vote up 5 votes
@Override
public boolean register(String fallbackPrefix, Command command, String label) {
    if (label == null) {
        label = command.getName();
    }
    label = label.trim().toLowerCase();
    fallbackPrefix = fallbackPrefix.trim().toLowerCase();

    boolean registered = this.registerAlias(command, false, fallbackPrefix, label);

    List<String> aliases = new ArrayList<>(Arrays.asList(command.getAliases()));

    for (Iterator<String> iterator = aliases.iterator(); iterator.hasNext(); ) {
        String alias = iterator.next();
        if (!this.registerAlias(command, true, fallbackPrefix, alias)) {
            iterator.remove();
        }
    }
    command.setAliases(aliases.stream().toArray(String[]::new));

    if (!registered) {
        command.setLabel(fallbackPrefix + ":" + label);
    }

    command.register(this);

    return registered;
}
 
Example 7
Project: gemoc-studio-modeldebugging   File: FilteredFileContentProvider.java   View Source Code Vote up 5 votes
@Override
public Object[] getChildren(final Object element) {
	List<Object> children = Arrays.asList(super.getChildren(element));
	List<Object> filteredChildren = new ArrayList<Object>(children);

	for (Object child : children) {
		if ((child instanceof IFile) && (!isAccepted((IFile)child))) {
			filteredChildren.remove(child);
		}
	}

	return filteredChildren.toArray();
}
 
Example 8
Project: sentry   File: CustomPersistentRememberMeServices.java   View Source Code Vote up 5 votes
/**
 * Validate the token and return it.
 */
private PersistentToken getPersistentToken(String[] cookieTokens) {
    if (cookieTokens.length != 2) {
        throw new InvalidCookieException("Cookie token did not contain " + 2 +
            " tokens, but contained '" + Arrays.asList(cookieTokens) + "'");
    }
    String presentedSeries = cookieTokens[0];
    String presentedToken = cookieTokens[1];
    PersistentToken token = persistentTokenRepository.findOne(presentedSeries);

    if (token == null) {
        // No series match, so we can't authenticate using this cookie
        throw new RememberMeAuthenticationException("No persistent token found for series id: " + presentedSeries);
    }

    // We have a match for this user/series combination
    log.info("presentedToken={} / tokenValue={}", presentedToken, token.getTokenValue());
    if (!presentedToken.equals(token.getTokenValue())) {
        // Token doesn't match series value. Delete this session and throw an exception.
        persistentTokenRepository.delete(token);
        throw new CookieTheftException("Invalid remember-me token (Series/token) mismatch. Implies previous " +
            "cookie theft attack.");
    }

    if (token.getTokenDate().plusDays(TOKEN_VALIDITY_DAYS).isBefore(LocalDate.now())) {
        persistentTokenRepository.delete(token);
        throw new RememberMeAuthenticationException("Remember-me login has expired");
    }
    return token;
}
 
Example 9
Project: OpenDA   File: UnstructuredMeshGeometryInfo.java   View Source Code Vote up 5 votes
/**
 * Designated constructor
 * @param coordinates array with dimensions of unstructured mesh
 * @param points     array with points of unstructured mesh
 */
public UnstructuredMeshGeometryInfo(IQuantityInfo[] coordinates, IArray points)
{
	if (coordinates.length != points.getDimensions()[1] ) {
		throw new RuntimeException(String.format("Number of coordinates %d does not agree with the dimensions of the points array %d.",coordinates.length, points.getNumberOfDimensions() ));
	}
	this.coordinates = new ArrayList<IQuantityInfo>(Arrays.asList(coordinates));
	this.points = new Array(points);
}
 
Example 10
Project: elements-of-programming-interviews-solutions   File: FindKthLargestTest.java   View Source Code Vote up 5 votes
@Test
public void findKth1() throws Exception {
    expected = 5;
    list = Arrays.asList(3,2,1,5,4);
    k = 1;

    test(expected, list, k);
}
 
Example 11
Project: tinkergraph-gremlin   File: TinkerGraphPlayTest.java   View Source Code Vote up 5 votes
@Test
@Ignore
public void testPlay7() throws Exception {
    /*TinkerGraph graph = TinkerGraph.open();
    graph.createIndex("name",Vertex.class);
    graph.io(GraphMLIo.build()).readGraph("/Users/marko/software/tinkerpop/tinkerpop3/data/grateful-dead.xml");*/
    //System.out.println(g.V().properties().key().groupCount().next());
    TinkerGraph graph = TinkerFactory.createModern();
    GraphTraversalSource g = graph.traversal();
    final List<Supplier<GraphTraversal<?, ?>>> traversals = Arrays.asList(
            () -> g.V().out().as("v").match(
                    __.as("v").outE().count().as("outDegree"),
                    __.as("v").inE().count().as("inDegree")).select("v", "outDegree", "inDegree").by(valueMap()).by().by().local(union(select("v"), select("inDegree", "outDegree")).unfold().fold())
    );

    traversals.forEach(traversal -> {
        logger.info("pre-strategy:  {}", traversal.get());
        logger.info("post-strategy: {}", traversal.get().iterate());
        logger.info(TimeUtil.clockWithResult(50, () -> traversal.get().toList()).toString());
    });
}
 
Example 12
Project: OpenCV_Android_Plus   File: MatOfFloat.java   View Source Code Vote up 5 votes
public List<Float> toList() {
    float[] a = toArray();
    Float ab[] = new Float[a.length];
    for(int i=0; i<a.length; i++)
        ab[i] = a[i];
    return Arrays.asList(ab);
}
 
Example 13
Project: primeval-reflex   File: MethodArgumentsGeneratorTest.java   View Source Code Vote up 4 votes
@Test
public void test() throws Exception {

    Method method = SharedProxyUtils.getMethodUnchecked(TheoreticalDelegate.class, "test", PrintStream.class, int.class,
            byte.class,
            String.class);
    List<Parameter> parameters = Arrays.asList(method.getParameters());

    String methodArgsClassName = MethodArgumentsGenerator.getName(TheoreticalDelegate.class, method, 0);

    // Practical to debug the generated bytecode with javap -c
    // Files.write(File.createTempFile("test", ".class").toPath(), bytecode);

    ProxyClassLoader dynamicClassLoader = new ProxyClassLoader(
            MethodArgumentsGeneratorTest.class.getClassLoader());
    dynamicClassLoader.declareClassToProxy(TheoreticalDelegate.class, new Class<?>[0], new Method[] { method },
            m -> true);
    Class<?> genClass = dynamicClassLoader.loadClass(methodArgsClassName);

    Arguments args = (Arguments) genClass
            .getConstructor(List.class, PrintStream.class, int.class, byte.class, String.class)
            .newInstance(parameters, System.out, 5, (byte) 42, "foo");

    assertThat(args.parameters()).isSameAs(parameters);

    PrintStream ps = args.objectArg("ps");
    assertThat(ps).isSameAs(System.out);

    String foo = args.objectArg("s");
    assertThat(foo).isEqualTo("foo");

    byte b = args.byteArg("b");
    assertThat(b).isEqualTo((byte) 42);

    int i = args.intArg("i");
    assertThat(i).isEqualTo(5);

    assertThatThrownBy(() -> {
        args.objectArg("unknown");
    }).isInstanceOf(IllegalArgumentException.class)
            .hasMessage("No Object parameter named unknown").hasNoCause();

    assertThatThrownBy(() -> {
        args.floatArg("radius");
    }).isInstanceOf(IllegalArgumentException.class)
            .hasMessage("No float parameter named radius").hasNoCause();

    ArgumentsUpdater updater = args.updater();
    Arguments arguments = updater.update();

    assertThat(arguments).isEqualTo(args);

    Arguments args2 = updater.setObjectArg("s", "bar").update();
    assertThat(args2.objectArg("s", String.class)).isEqualTo("bar");

    Arguments args3 = updater.setIntArg("i", 30).update();
    assertThat(args3.intArg("i")).isEqualTo(30);

}
 
Example 14
Project: sstable-adaptor   File: Tuples.java   View Source Code Vote up 4 votes
public List<ByteBuffer> getElements()
{
    return Arrays.asList(elements);
}
 
Example 15
Project: aws-sdk-java-v2   File: ValueList.java   View Source Code Vote up 4 votes
/**
 * Appends the given value to this list as a set of BigDecimals.
 */
public ValueList appendNumberSet(BigDecimal... val) {
    super.append(new LinkedHashSet<BigDecimal>(Arrays.asList(val)));
    return this;
}
 
Example 16
Project: nonull   File: Filter.java   View Source Code Vote up 4 votes
protected List<String> packagePrefix() {
    return Arrays.asList();
}
 
Example 17
Project: alvisnlp   File: AlvisNLPAnnotationProcessor.java   View Source Code Vote up 4 votes
@Override
	public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
		try {
			String prefix = ctx.hasOption("classPrefix") ? ctx.getOption("classPrefix") : "Concrete";

			if (annotations.contains(ctx.getModuleAnnotation())) {				
				String moduleFactoryName = ctx.getOption("moduleFactoryName");
				String dataClass = ctx.getOption("dataClass");
				String sequenceImplementationClass = ctx.getOption("sequenceImplementationClass");
				String factoryInterface = ctx.getOption("factoryInterface");
				String shellModule = ctx.getOption("shellModule");
				ModuleFactoryModel moduleFactory = new ModuleFactoryModel(moduleFactoryName, dataClass, sequenceImplementationClass, factoryInterface, prefix, shellModule);

				ctx.note("processing module sources");
				for (TypeElement moduleElement : ElementFilter.typesIn(roundEnv.getElementsAnnotatedWith(ctx.getModuleAnnotation()))) {
					ModuleModel module = new ModuleModel(ctx, moduleElement);
					moduleFactory.addModule(ctx, module);
				}

				ctx.note("generating module factory for data class " + dataClass + " (" + moduleFactory.moduleCount() + " modules, " + moduleFactory.betaCount() + " beta, " + moduleFactory.obsoleteCount() + " obsolete)");
				moduleFactory.generateClass(ctx);
				ctx.note("generating module classes");
				moduleFactory.generateModules(ctx);
				// XXX broken in maven build
				//ctx.note("generating module documentation");
				//moduleFactory.generateModuleDocs(ctx);
				//ctx.note("generating module factory service");
				//moduleFactory.generateService(ctx);
			}

			if (annotations.contains(ctx.getConverterAnnotation())) {
				if (!ctx.hasOption("converterFactoryName")) {
					ctx.error("missing option -AconverterFactoryName");
					return true;
				}
				String converterFactoryName = ctx.getOption("converterFactoryName");
				List<String> resourceBases = Arrays.asList(ctx.getOption("resourceBases").split(":"));
				ConverterFactoryModel converterFactory = new ConverterFactoryModel(converterFactoryName, resourceBases);
				ctx.note("processing converter sources");
				for (TypeElement converterElement : ElementFilter.typesIn(roundEnv.getElementsAnnotatedWith(ctx.getConverterAnnotation()))) {
					ConverterModel converter = new ConverterModel(ctx, converterElement);
					converterFactory.addConverter(converter);
				}
				ctx.note("generating converter factory class");
				converterFactory.generateClass(ctx);
				ctx.note("generating converter documentation");
				converterFactory.generateConvertersDoc(ctx);
				//ctx.note("generating converter factory service");
				//converterFactory.generateService(ctx);
			}

			if (annotations.contains(ctx.getLibraryAnnotation())) {
				for (TypeElement libraryElement : ElementFilter.typesIn(roundEnv.getElementsAnnotatedWith(ctx.getLibraryAnnotation()))) {
					ctx.note("generating library class: " + libraryElement.getAnnotation(Library.class).value());
					LibraryModel libModel = new LibraryModel(ctx, libraryElement, prefix);
					libModel.generateClass(ctx);
					// XXX broken by maven
					// libModel.generateDocumentation(ctx);
				}
			}
		}
		catch (TransformerException te) {
			ctx.error("error while processing source: " + te.getMessage());
		}
		catch (IOException ioe) {
			ctx.error("error while processing source: " + ioe.getMessage());
		}
		catch (ModelException me) {
			ctx.error(me.getMessage());
		}
//		catch (XPathExpressionException xpee) {
//			ctx.error(xpee.getMessage());
//		}
		catch (TransformerFactoryConfigurationError tfce) {
			ctx.error(tfce.getMessage());
		}
//		catch (SAXException saxe) {
//			ctx.error(saxe.getMessage());
//		}
		return true;
	}
 
Example 18
Project: morf   File: TestH2Dialect.java   View Source Code Vote up 4 votes
/**
 * @see org.alfasoftware.morf.jdbc.AbstractSqlDialectTest#expectedAlterTableAlterStringColumnStatement()
 */
@Override
protected List<String> expectedAlterTableAlterStringColumnStatement() {
  return Arrays.asList("ALTER TABLE Test ALTER COLUMN stringField VARCHAR(6)");
}
 
Example 19
Project: openjdk-jdk10   File: TestClose2.java   View Source Code Vote up 4 votes
void run() throws IOException {
    File testSrc = new File(System.getProperty("test.src"));
    File testClasses = new File(System.getProperty("test.classes"));

    JavacTool tool = (JavacTool) ToolProvider.getSystemJavaCompiler();
    final ClassLoader cl = getClass().getClassLoader();
    Context c = new Context();
    StandardJavaFileManager fm = new JavacFileManager(c, true, null) {
        @Override
        protected ClassLoader getClassLoader(URL[] urls) {
            return new URLClassLoader(urls, cl) {
                @Override
                public void close() throws IOException {
                    System.err.println(getClass().getName() + " closing");
                    TestClose2.this.closedCount++;
                    TestClose2.this.closedIsLast = true;
                    super.close();
                }
            };
        }
    };

    fm.setLocation(StandardLocation.CLASS_OUTPUT,
            Collections.singleton(new File(".")));
    fm.setLocation(StandardLocation.ANNOTATION_PROCESSOR_PATH,
            Collections.singleton(testClasses));
    Iterable<? extends JavaFileObject> files =
            fm.getJavaFileObjects(new File(testSrc, TestClose2.class.getName() + ".java"));
    List<String> options = Arrays.asList(
            "--add-exports", "jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED",
            "--add-exports", "jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED",
            "--add-exports", "jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED",
            "-processor", TestClose2.class.getName());

    JavacTask task = tool.getTask(null, fm, null, options, null, files);
    task.setTaskListener(this);

    if (!task.call())
        throw new Error("compilation failed");

    if (closedCount == 0)
        throw new Error("no closing message");
    else if (closedCount > 1)
        throw new Error(closedCount + " closed messages");

    if (!closedIsLast)
        throw new Error("closing message not last");
}
 
Example 20
Project: shuffleboard   File: ListUtilsTest.java   View Source Code Vote up 4 votes
@Test
public void testJoiningNoSeparatorsNoBookends() {
  List<String> list = Arrays.asList(foo, bar);
  List<String> result = list.stream().collect(joining(nullSupplier, nullSupplier, nullSupplier));
  assertEquals(list, result);
}