Java Code Examples for java.util.Collections#addAll()

The following examples show how to use java.util.Collections#addAll() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AbstractProfProvider.java    From pcgen with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Returns true if this AbstractProfProvider provides proficiency with the
 * given Equipment TYPE. This only tests against the Equipment TYPE
 * reference list provided during construction of the AbstractProfProvider.
 * 
 * @param typeString
 *            The TYPE of Equipment to be tested to see if this
 *            AbstractProfProvider provides proficiency with the given
 *            Equipment TYPE
 * @return true if this AbstractProfProvider provides proficiency with the
 *         given Equipment TYPE.
 */
@Override
@SuppressWarnings("PMD.AvoidBranchingStatementAsLastInLoop")
public boolean providesEquipmentType(String typeString)
{
	if (typeString == null || typeString.isEmpty())
	{
		return false;
	}
	Set<String> types = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
	Collections.addAll(types, typeString.split("\\."));
	REF: for (CDOMReference<Equipment> ref : byEquipType)
	{
		StringTokenizer tok = new StringTokenizer(ref.getLSTformat(false).substring(5), ".");
		while (tok.hasMoreTokens())
		{
			if (!types.contains(tok.nextToken()))
			{
				continue REF;
			}
		}
		return true;
	}
	return false;
}
 
Example 2
Source File: FilterUtil.java    From CEC-Automatic-Annotation with Apache License 2.0 5 votes vote down vote up
@Test
@Ignore
public void testListAndSet() {
	List<String> list = new ArrayList<String>();
	Set<String> set = new TreeSet<String>();
	Collections.addAll(list, "wo", "woai", "woaini", "wo");
	set.addAll(list);// 将List转成Set
	list.clear();
	list.addAll(set);// 将Set转成List
	int index = 0;
	System.out.println(list.get(index++));
	System.out.println(list);
	System.out.println(set);
}
 
Example 3
Source File: StandAloneTest.java    From score with Apache License 2.0 5 votes vote down vote up
private void registerEventListener(String... eventTypes) {
    Set<String> handlerTypes = new HashSet<>();
    Collections.addAll(handlerTypes, eventTypes);
    eventBus.subscribe(new ScoreEventListener() {
        @Override
        public void onEvent(ScoreEvent event) {
            logger.info("Listener " + this.toString() + " invoked on type: " + event.getEventType() + " with data: " + event.getData());
            eventQueue.add(event);
        }
    }, handlerTypes);
}
 
Example 4
Source File: ConjunctionDISI.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private static void addIterator(DocIdSetIterator disi, List<DocIdSetIterator> allIterators) {
  if (disi.getClass() == ConjunctionDISI.class) { // Check for exactly this class for collapsing
    ConjunctionDISI conjunction = (ConjunctionDISI) disi;
    // subconjuctions have already split themselves into two phase iterators and others, so we can take those
    // iterators as they are and move them up to this conjunction
    allIterators.add(conjunction.lead1);
    allIterators.add(conjunction.lead2);
    Collections.addAll(allIterators, conjunction.others);
  } else {
    allIterators.add(disi);
  }
}
 
Example 5
Source File: RowCountValidatorImportTest.java    From aliyun-maxcompute-data-collectors with Apache License 2.0 5 votes vote down vote up
public void testValidationOptionsParsedCorrectly() throws Exception {
  String[] types = {"INT NOT NULL PRIMARY KEY", "VARCHAR(32)", "VARCHAR(32)"};
  String[] insertVals = {"1", "'Bob'", "'sales'"};

  try {
    createTableWithColTypes(types, insertVals);

    String[] args = getArgv(true, null, getConf());
    ArrayList<String> argsList = new ArrayList<String>();
    argsList.add("--validator");
    argsList.add("org.apache.sqoop.validation.RowCountValidator");
    argsList.add("--validation-threshold");
    argsList.add("org.apache.sqoop.validation.AbsoluteValidationThreshold");
    argsList.add("--validation-failurehandler");
    argsList.add("org.apache.sqoop.validation.AbortOnFailureHandler");
    Collections.addAll(argsList, args);

    assertTrue("Validate option missing.", argsList.contains("--validate"));
    assertTrue("Validator option missing.", argsList.contains("--validator"));

    String[] optionArgs = toStringArray(argsList);

    SqoopOptions validationOptions = new ImportTool().parseArguments(
      optionArgs, getConf(), getSqoopOptions(getConf()), true);
    assertEquals(RowCountValidator.class,
      validationOptions.getValidatorClass());
    assertEquals(AbsoluteValidationThreshold.class,
      validationOptions.getValidationThresholdClass());
    assertEquals(AbortOnFailureHandler.class,
      validationOptions.getValidationFailureHandlerClass());
  } catch (Exception e) {
    fail("The validation options are passed correctly: " + e.getMessage());
  } finally {
    dropTableIfExists(getTableName());
  }
}
 
Example 6
Source File: SandalsOfNature.java    From shattered-pixel-dungeon-gdx with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void restoreFromBundle( Bundle bundle ) {
	super.restoreFromBundle(bundle);
	if (level() > 0) name = Messages.get(this, "name_" + level());
	if (bundle.contains(SEEDS))
		Collections.addAll(seeds , bundle.getClassArray(SEEDS));
	if (level() == 1)  image = ItemSpriteSheet.ARTIFACT_SHOES;
	else if (level() == 2)  image = ItemSpriteSheet.ARTIFACT_BOOTS;
	else if (level() >= 3)  image = ItemSpriteSheet.ARTIFACT_GREAVES;
}
 
Example 7
Source File: SsManifestParser.java    From K-Sonic with MIT License 5 votes vote down vote up
private static List<byte[]> buildCodecSpecificData(String codecSpecificDataString) {
  ArrayList<byte[]> csd = new ArrayList<>();
  if (!TextUtils.isEmpty(codecSpecificDataString)) {
    byte[] codecPrivateData = Util.getBytesFromHexString(codecSpecificDataString);
    byte[][] split = CodecSpecificDataUtil.splitNalUnits(codecPrivateData);
    if (split == null) {
      csd.add(codecPrivateData);
    } else {
      Collections.addAll(csd, split);
    }
  }
  return csd;
}
 
Example 8
Source File: ExpandedValueType.java    From arma-intellij-plugin with MIT License 5 votes vote down vote up
/**
 * Create an instance with the specified {@link ValueType} instances. This will set {@link #getNumOptionalValues()} to 0.
 *
 * @param isUnbounded      true if the last element in valueTypes is repeating, false otherwise
 * @param polymorphicTypes polymorphic types to use for {@link #getPolymorphicTypes()}
 * @param valueTypes       value types to use
 */
public ExpandedValueType(boolean isUnbounded, @NotNull List<ValueType> polymorphicTypes, @NotNull ValueType... valueTypes) {
	this.isUnbounded = isUnbounded;
	this.polymorphicTypes = polymorphicTypes;

	this.valueTypes = new ArrayList<>(valueTypes.length);
	Collections.addAll(this.valueTypes, valueTypes);
	numOptionalValues = 0;
}
 
Example 9
Source File: Util.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Converts varargs from an update call to a list of objects, ensuring that the arguments
 * alternate between String/FieldPath and Objects.
 *
 * @param fieldPathOffset The offset of the first field path in the original update API (used as
 *     the index in error messages)
 */
public static List<Object> collectUpdateArguments(
    int fieldPathOffset, Object field, Object val, Object... fieldsAndValues) {
  if (fieldsAndValues.length % 2 == 1) {
    throw new IllegalArgumentException(
        "Missing value in call to update().  There must be an even number of "
            + "arguments that alternate between field names and values");
  }
  List<Object> argumentList = new ArrayList<>();
  argumentList.add(field);
  argumentList.add(val);
  Collections.addAll(argumentList, fieldsAndValues);

  for (int i = 0; i < argumentList.size(); i += 2) {
    Object fieldPath = argumentList.get(i);
    if (!(fieldPath instanceof String) && !(fieldPath instanceof FieldPath)) {
      throw new IllegalArgumentException(
          "Excepted field name at argument position "
              + (i + fieldPathOffset + 1)
              + " but got "
              + fieldPath
              + " in call to update.  The arguments to update "
              + "should alternate between field names and values");
    }
  }

  return argumentList;
}
 
Example 10
Source File: MailActivityBehavior.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
private void getFilesFromFields(Expression expression, DelegateExecution execution, List<File> files, List<DataSource> dataSources) {
    Object value = checkAllowedTypes(expression, execution);
    if (value != null) {
        if (value instanceof File) {
            files.add((File) value);
        } else if (value instanceof String) {
            files.add(new File((String) value));
        } else if (value instanceof File[]) {
            Collections.addAll(files, (File[]) value);
        } else if (value instanceof String[]) {
            String[] paths = (String[]) value;
            for (String path : paths) {
                files.add(new File(path));
            }
        } else if (value instanceof DataSource) {
            dataSources.add((DataSource) value);
        } else if (value instanceof DataSource[]) {
            for (DataSource ds : (DataSource[]) value) {
                if (ds != null) {
                    dataSources.add(ds);
                }
            }
        }
    }
    for (Iterator<File> it = files.iterator(); it.hasNext(); ) {
        File file = it.next();
        if (!fileExists(file)) {
            it.remove();
        }
    }
}
 
Example 11
Source File: ImmutableSet.java    From fresco with MIT License 4 votes vote down vote up
public static <E> ImmutableSet<E> of(E... elements) {
  HashSet<E> set = new HashSet<>(elements.length);
  Collections.addAll(set, elements);
  return new ImmutableSet<>(set);
}
 
Example 12
Source File: Lists.java    From Ardulink-2 with Apache License 2.0 4 votes vote down vote up
public static <T> List<T> newArrayList(T... values) {
	List<T> list = new ArrayList<T>();
	Collections.addAll(list, values);
	return list;
}
 
Example 13
Source File: DgmConverter.java    From groovy with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws IOException {
    String targetDirectory = "target/classes/";
    boolean info = (args.length == 1 && args[0].equals("--info"))
            || (args.length==2 && args[0].equals("--info"));
    if (info && args.length==2) {
        targetDirectory = args[1];
        if (!targetDirectory.endsWith("/")) targetDirectory += "/";
    }
    List<CachedMethod> cachedMethodsList = new ArrayList<CachedMethod>();
    for (Class aClass : DefaultGroovyMethods.DGM_LIKE_CLASSES) {
        Collections.addAll(cachedMethodsList, ReflectionCache.getCachedClass(aClass).getMethods());
    }
    final CachedMethod[] cachedMethods = cachedMethodsList.toArray(CachedMethod.EMPTY_ARRAY);

    List<GeneratedMetaMethod.DgmMethodRecord> records = new ArrayList<GeneratedMetaMethod.DgmMethodRecord>();

    int cur = 0;
    for (CachedMethod method : cachedMethods) {
        if (!method.isStatic() || !method.isPublic())
            continue;

        if (method.getAnnotation(Deprecated.class) != null)
            continue;

        if (method.getParameterTypes().length == 0)
            continue;

        final Class returnType = method.getReturnType();

        final String className = "org/codehaus/groovy/runtime/dgm$" + cur++;

        GeneratedMetaMethod.DgmMethodRecord record = new GeneratedMetaMethod.DgmMethodRecord();
        records.add(record);

        record.methodName = method.getName();
        record.returnType = method.getReturnType();
        record.parameters = method.getNativeParameterTypes();
        record.className = className;

        ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
        cw.visit(V1_3, ACC_PUBLIC, className, null, "org/codehaus/groovy/reflection/GeneratedMetaMethod", null);

        createConstructor(cw);

        final String methodDescriptor = BytecodeHelper.getMethodDescriptor(returnType, method.getNativeParameterTypes());

        createInvokeMethod(method, cw, returnType, methodDescriptor);

        createDoMethodInvokeMethod(method, cw, className, returnType, methodDescriptor);

        createIsValidMethodMethod(method, cw, className);

        cw.visitEnd();

        final byte[] bytes = cw.toByteArray();

        File targetFile = new File(targetDirectory + className + ".class").getCanonicalFile();
        targetFile.getParentFile().mkdirs();

        try (final FileOutputStream fileOutputStream = new FileOutputStream(targetFile)) {
            fileOutputStream.write(bytes);
            fileOutputStream.flush();
        }
    }

    GeneratedMetaMethod.DgmMethodRecord.saveDgmInfo(records, targetDirectory+"/META-INF/dgminfo");
    if (info)
        System.out.println("Saved " + cur + " dgm records to: "+targetDirectory+"/META-INF/dgminfo");
}
 
Example 14
Source File: CurveOptions.java    From Curve-Fit with Apache License 2.0 4 votes vote down vote up
public CurveOptions add(LatLng... points) {
    Collections.addAll(this.latLngList, points);
    return this;
}
 
Example 15
Source File: CollectionsDemo04.java    From javacore with Creative Commons Attribution Share Alike 4.0 International 4 votes vote down vote up
public static void main(String[] args) {
    List<String> all = new ArrayList<String>();    // 返回空的 List集合
    Collections.addAll(all, "MLDN", "LXH", "mldnjava");
    int point = Collections.binarySearch(all, "LXH");    // 检索数据
    System.out.println("检索结果:" + point);
}
 
Example 16
Source File: Config.java    From remote-monitoring-services-java with MIT License 4 votes vote down vote up
/**
 * Client authorization configuration
 */
public IClientAuthConfig getClientAuthConfig() {
    if (this.clientAuthConfig != null) return this.clientAuthConfig;

    // Default to True unless explicitly disabled
    Boolean authRequired = !data.hasPath(AUTH_REQUIRED_KEY)
        || data.getString(AUTH_REQUIRED_KEY).isEmpty()
        || data.getBool(AUTH_REQUIRED_KEY);

    String authServiceUrl = data.getString(AUTH_WEB_SERVICE_URL_KEY);

    // Default to JWT
    String authType = "JWT";
    if (data.hasPath(AUTH_REQUIRED_KEY)) {
        authType = data.getString(AUTH_TYPE_KEY);
    }

    // Default to RS256, RS384, RS512
    HashSet<String> jwtAllowedAlgos = new HashSet<>();
    jwtAllowedAlgos.add("RS256");
    jwtAllowedAlgos.add("RS384");
    jwtAllowedAlgos.add("RS512");
    if (data.hasPath(JWT_ALGOS_KEY)) {
        jwtAllowedAlgos.clear();
        Collections.addAll(
            jwtAllowedAlgos,
            data.getString(JWT_ALGOS_KEY).split(","));
    }

    // Default to empty, no issuer
    String jwtIssuer = "";
    if (data.hasPath(JWT_ISSUER_KEY)) {
        jwtIssuer = data.getString(JWT_ISSUER_KEY);
    }

    // Default to empty, no audience
    String jwtAudience = "";
    if (data.hasPath(JWT_AUDIENCE_KEY)) {
        jwtAudience = data.getString(JWT_AUDIENCE_KEY);
    }

    // Default to 2 minutes
    Duration jwtClockSkew = Duration.ofSeconds(120);
    if (data.hasPath(JWT_AUDIENCE_KEY)) {
        jwtClockSkew = data.getDuration(JWT_CLOCK_SKEW_KEY);
    }

    this.clientAuthConfig = new ClientAuthConfig(
        authRequired,
        authServiceUrl,
        authType,
        jwtAllowedAlgos,
        jwtIssuer,
        jwtAudience,
        jwtClockSkew);

    return this.clientAuthConfig;
}
 
Example 17
Source File: AnalysisEngineLaunchConfigurationDelegate.java    From uima-uimaj with Apache License 2.0 4 votes vote down vote up
/**
   * Adds the launcher and uima core jar to the class path,
   * depending on normal mode or PDE development mode.
   */
  @Override
  public String[] getClasspath(ILaunchConfiguration configuration) throws CoreException {
    
    // The class path already contains the jars which are specified in the Classpath tab
    
    List<String> extendedClasspath = new ArrayList<>();
    Collections.addAll(extendedClasspath, super.getClasspath(configuration));
    
    // Normal mode, add the launcher plugin and uima runtime jar to the classpath
    try {
      if (!Platform.inDevelopmentMode()) {     
        // Add this plugin jar to the classpath 
        extendedClasspath.add(pluginIdToJarPath(LauncherPlugin.ID)); }
      else {
        // When running inside eclipse with PDE in development mode the plugins
        // are not installed inform of jar files and the classes must be loaded
        // from the target/classes folder or target/org.apache.uima.runtime.*.jar file
        extendedClasspath.add(pluginIdToJarPath(LauncherPlugin.ID) + "target/classes");
      }
      // UIMA jar should be added the end of the class path, because user uima jars
      // (maybe a different version) should appear first on the class path

      // Add org.apache.uima.runtime jar to class path
      Bundle bundle = LauncherPlugin.getDefault().getBundle("org.apache.uima.runtime");
      
      // Ignore the case when runtime bundle does not exist ...
      if (bundle != null) {
        // find entries: starting point, pattern, whether or not to recurse
        //   all the embedded jars are at the top level, no recursion needed
        //   All the jars are not needed - only the uimaj core one
        //     any other jars will be provided by the launching project's class path
        //     uimaj-core provided because the launcher itself needs uimaj-core classes
        //  Found empirically that recursion is need to find the jar in development mode
        Enumeration<?> jarEnum = bundle.findEntries("/", "uimaj-core*.jar", Platform.inDevelopmentMode());
        while (jarEnum != null && jarEnum.hasMoreElements()) {
          URL element = (URL) jarEnum.nextElement();
          extendedClasspath.add(FileLocator.toFileURL(element).getFile());
        }
      }        
      // adds things like the top level metainf info, 
      // probably not required in most cases
      extendedClasspath.add(pluginIdToJarPath("org.apache.uima.runtime"));
    } catch (IOException e) {
      throw new CoreException(new Status(IStatus.ERROR, LauncherPlugin.ID, IStatus.OK, 
              "Failed to compose classpath!", e));
    }
    
    // Dump classpath
//    for (String cp : extendedClasspath) {
//      System.out.println("Uima Launcher CP entry: " + cp);
//    }
    return extendedClasspath.toArray(new String[extendedClasspath.size()]);
  }
 
Example 18
Source File: ImageFileTypeResolver.java    From scipio-erp with Apache License 2.0 3 votes vote down vote up
public GifFileType() {
    Collections.addAll(MAGIC_NUMBERS,

    new MagicNumber("474946383761", null, "003B", 0, "Graphics interchange format file", "gif"),

    new MagicNumber("474946383961", null, "003B", 0, "Graphics interchange format file", "gif")

    );
}
 
Example 19
Source File: AsynchronousFileChannel.java    From dragonwell8_jdk with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Opens or creates a file for reading and/or writing, returning an
 * asynchronous file channel to access the file.
 *
 * <p> An invocation of this method behaves in exactly the same way as the
 * invocation
 * <pre>
 *     ch.{@link #open(Path,Set,ExecutorService,FileAttribute[])
 *       open}(file, opts, null, new FileAttribute&lt;?&gt;[0]);
 * </pre>
 * where {@code opts} is a {@code Set} containing the options specified to
 * this method.
 *
 * <p> The resulting channel is associated with default thread pool to which
 * tasks are submitted to handle I/O events and dispatch to completion
 * handlers that consume the result of asynchronous operations performed on
 * the resulting channel.
 *
 * @param   file
 *          The path of the file to open or create
 * @param   options
 *          Options specifying how the file is opened
 *
 * @return  A new asynchronous file channel
 *
 * @throws  IllegalArgumentException
 *          If the set contains an invalid combination of options
 * @throws  UnsupportedOperationException
 *          If the {@code file} is associated with a provider that does not
 *          support creating file channels, or an unsupported open option is
 *          specified
 * @throws  IOException
 *          If an I/O error occurs
 * @throws  SecurityException
 *          If a security manager is installed and it denies an
 *          unspecified permission required by the implementation.
 *          In the case of the default provider, the {@link
 *          SecurityManager#checkRead(String)} method is invoked to check
 *          read access if the file is opened for reading. The {@link
 *          SecurityManager#checkWrite(String)} method is invoked to check
 *          write access if the file is opened for writing
 */
public static AsynchronousFileChannel open(Path file, OpenOption... options)
    throws IOException
{
    Set<OpenOption> set = new HashSet<OpenOption>(options.length);
    Collections.addAll(set, options);
    return open(file, set, null, NO_ATTRIBUTES);
}
 
Example 20
Source File: SimpleJndiBeanFactory.java    From spring-analysis-note with MIT License 2 votes vote down vote up
/**
 * Set a list of names of shareable JNDI resources,
 * which this factory is allowed to cache once obtained.
 * @param shareableResources the JNDI names
 * (typically within the "java:comp/env/" namespace)
 */
public void setShareableResources(String... shareableResources) {
	Collections.addAll(this.shareableResources, shareableResources);
}