Example usage for java.util Collections addAll

List of usage examples for java.util Collections addAll

Introduction

In this page you can find the example usage for java.util Collections addAll.

Prototype

@SafeVarargs
public static <T> boolean addAll(Collection<? super T> c, T... elements) 

Source Link

Document

Adds all of the specified elements to the specified collection.

Usage

From source file:kr.ac.korea.dbserver.parser.SQLAnalyzer.java

@Override
public Aggregation visitGroupby_clause(SQLParser.Groupby_clauseContext ctx) {
    Aggregation clause = new Aggregation();

    // If grouping group is not empty
    if (ctx.grouping_element_list().grouping_element().get(0).empty_grouping_set() == null) {
        int elementSize = ctx.grouping_element_list().grouping_element().size();
        ArrayList<GroupElement> groups = new ArrayList<GroupElement>(elementSize + 1);
        ArrayList<Expr> ordinaryExprs = null;
        int groupSize = 1;
        groups.add(null);/*from   w w w  .  j av a2  s  .  c o  m*/

        for (int i = 0; i < elementSize; i++) {
            SQLParser.Grouping_elementContext element = ctx.grouping_element_list().grouping_element().get(i);
            if (element.ordinary_grouping_set() != null) {
                if (ordinaryExprs == null) {
                    ordinaryExprs = new ArrayList<Expr>();
                }
                Collections.addAll(ordinaryExprs,
                        getRowValuePredicandsFromOrdinaryGroupingSet(element.ordinary_grouping_set()));
            } else if (element.rollup_list() != null) {
                groupSize++;
                groups.add(new GroupElement(GroupType.Rollup,
                        getRowValuePredicandsFromOrdinaryGroupingSetList(element.rollup_list().c)));
            } else if (element.cube_list() != null) {
                groupSize++;
                groups.add(new GroupElement(GroupType.Cube,
                        getRowValuePredicandsFromOrdinaryGroupingSetList(element.cube_list().c)));
            }
        }

        if (ordinaryExprs != null) {
            groups.set(0, new GroupElement(GroupType.OrdinaryGroup,
                    ordinaryExprs.toArray(new Expr[ordinaryExprs.size()])));
            clause.setGroups(groups.subList(0, groupSize).toArray(new GroupElement[groupSize]));
        } else if (groupSize > 1) {
            clause.setGroups(groups.subList(1, groupSize).toArray(new GroupElement[groupSize - 1]));
        }
    }

    return clause;
}

From source file:com.aliyun.odps.mapred.BridgeJobRunner.java

@SuppressWarnings("unchecked")
protected void setUp() throws OdpsException {
    // Prepare additional config parameters

    // merge streaming job alias resources if exist
    if (job.get("stream.temp.resource.alias") != null) {
        String aliasJson = job.get("stream.temp.resource.alias");
        try {//  w w w.  ja  v a2  s . c o m
            aliasToTempResource
                    .putAll((Map<String, String>) JSON.parseObject(aliasJson, Map.class, Feature.OrderedField));
        } catch (JSONException e) {
            throw new OdpsException("parse stream temp resource alias json failed!", e);
        }
    }
    // for user defined partitioner, estimate reduce number if not set
    boolean isEstimateReduceNum = (job.getPartitionerClass() != null)
            && (job.get("odps.stage.reducer.num") == null);
    long inputSize = 0;
    // Expand input columns if applicable.
    TableInfo[] infos = InputUtils.getTables(job);
    // for multi inputs not allow inner output in mapper
    if (infos != null && infos.length > 1) {
        job.setMapperInnerOutputEnable(false);
    }
    String project = metaExplorer.getDefaultProject();
    boolean changed = false;
    if (infos != null) {
        for (int i = 0; i < infos.length; i++) {
            TableInfo info = infos[i];
            if (info.getProjectName() == null) {
                changed = true;
                info.setProjectName(project);
            }

            Table tbl = metaExplorer.getTable(info.getProjectName(), info.getTableName());
            List<Column> schema = tbl.getSchema().getColumns();
            String[] inputCols = getInputColumnsFromCommandSettings(job, info);
            if (inputCols.length == 0 && info.getCols() == null) {
                changed = true;
                Column[] columns = schema.toArray(new Column[schema.size()]);
                job.setInputSchema(info, columns);
                info.setCols(SchemaUtils.getNames(columns));
            } else {
                if (inputCols.length == 0) {
                    inputCols = info.getCols();
                }
                Column[] columns = new Column[inputCols.length];
                for (int k = 0; k < inputCols.length; k++) {
                    String colName = inputCols[k];
                    for (Column c : schema) {
                        if (c.getName().equalsIgnoreCase(colName)) {
                            columns[k] = c;
                            break;
                        }
                    }
                }
                job.setInputSchema(info, columns);
            }
            if (isEstimateReduceNum) {
                PartitionSpec part = info.getPartitionSpec();
                if (!part.isEmpty()) {
                    // for partition table input
                    inputSize += tbl.getPartition(part).getSize();
                } else {
                    inputSize += tbl.getSize();
                }
            }
        }
    }
    if (changed) {
        InputUtils.setTables(infos, job);
    }
    if (isEstimateReduceNum) {
        job.setNumReduceTasks(estimateReduceNum(inputSize, job));
    }

    //add project information for volume if necessary
    changed = false;
    VolumeInfo[] volumeInfos = InputUtils.getVolumes(job);
    if (volumeInfos != null) {
        for (VolumeInfo volume : volumeInfos) {
            if (volume.getProjectName() == null) {
                changed = true;
                volume.setProjectName(project);
            }
        }
    }
    if (changed) {
        InputUtils.setVolumes(volumeInfos, job);
    }
    changed = false;
    volumeInfos = OutputUtils.getVolumes(job);
    if (volumeInfos != null) {
        for (VolumeInfo volume : volumeInfos) {
            if (volume.getProjectName() == null) {
                changed = true;
                volume.setProjectName(project);
            }
        }
    }
    if (changed) {
        OutputUtils.setVolumes(volumeInfos, job);
    }

    // Expand output columns.
    infos = OutputUtils.getTables(job);
    if (infos == null) {
        job.setOutputSchema(new Column[] { new Column("nil", OdpsType.STRING) }, TableInfo.DEFAULT_LABEL);
    } else {
        for (TableInfo info : infos) {
            if (info.getProjectName() == null) {
                info.setProjectName(project);
            }
            List<Column> schema = metaExplorer.getTable(info.getProjectName(), info.getTableName()).getSchema()
                    .getColumns();
            Column[] schemaArray = schema.toArray(new Column[schema.size()]);
            info.setCols(SchemaUtils.getNames(schemaArray));
            job.setOutputSchema(schemaArray, info.getLabel());
        }
        OutputUtils.setTables(infos, job);
    }

    processTempResources();

    // Adding jobconf jar.
    ByteArrayOutputStream jarOut = null;
    try {
        jarOut = createJarArchive();
        jarOut.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    String resName = metaExplorer.addTempResourceWithRetry(new ByteArrayInputStream(jarOut.toByteArray()),
            jobId + ".jar", Resource.Type.JAR);
    aliasToTempResource.put("jobconf.jar", resName);

    applyFrameworkResources();

    List<String> totalRes = new ArrayList<String>();
    String[] resources = job.getResources();
    if (resources != null) {
        Collections.addAll(totalRes, resources);
    }
    totalRes.addAll(aliasToTempResource.keySet());
    job.setResources(StringUtils.join(totalRes, ","));
}

From source file:com.liferay.ide.portlet.core.PluginPackageModel.java

public void swapDependencies(String property, String dep1, String dep2) {
    String[] deps = null;/* ww  w.  j a v a  2  s. co m*/
    String depsValue = pluginPackageProperties.getString(property, null);

    if (depsValue != null) {
        deps = depsValue.split(","); //$NON-NLS-1$
    } else {
        deps = new String[0];
    }

    ArrayList<String> list = new ArrayList<String>();
    Collections.addAll(list, deps);

    int index1 = list.indexOf(dep1);
    int index2 = list.indexOf(dep2);
    list.set(index2, dep1);
    list.set(index1, dep2);

    String[] newValues = list.toArray(new String[0]);

    StringBuffer buffer = new StringBuffer();

    for (String val : newValues) {
        buffer.append(val + ","); //$NON-NLS-1$
    }

    String newValue = buffer.toString().substring(0, buffer.length() - 1);
    pluginPackageProperties.setProperty(property, newValue);

    flushProperties();

    fireModelChanged(new ModelChangedEvent(this, null, property, depsValue, newValue));
}

From source file:com.oneops.sensor.ws.SensorWsController.java

/**
 * Gets the cis states./* w  ww  .j  a v a2 s .c  om*/
 *
 * @param ciIdsAr array of ci ids
 * @return the cis states
 */
@RequestMapping(value = "/ops/states", method = RequestMethod.POST)
@ResponseBody
public List<Map<String, String>> getCisStatesPost(@RequestBody Long[] ciIdsAr) {
    List<Long> ciIds = new ArrayList<>();
    Collections.addAll(ciIds, ciIdsAr);
    return getCisStates(ciIds);
}

From source file:com.f16gaming.pathofexilestatistics.MainActivity.java

private void updateList(StatsResponse response, boolean hardcore, boolean refresh, boolean jump) {
    if (response == null) {
        // Something went wrong and we didn't even get a response body
        showToast(getString(R.string.retrieve_data_fail));
        hideProgress();//from w  w  w  . j av a2 s .  co  m
        return;
    }

    try {
        StatusLine status = response.getStatus();
        // Should probably make this handle status codes listed on PoE API
        if (status.getStatusCode() == HttpStatus.SC_OK) {
            String responseString = response.getResponseString();
            PoeEntry[] newEntries = PoeEntry.getEntriesFromJSONString(responseString);

            // This was a mode switch, refresh or jump; clear the previous entries
            // We also clear it if the offset is 0 (first execution or list reset)
            if (offset == 0 || hardcore != showHardcore || (refresh && refreshOffset == refreshTopOffset)
                    || jump)
                poeEntries.clear();

            // Add the newly loaded entries
            Collections.addAll(poeEntries, newEntries);

            // Continue loading entries if this is a refresh and it's not done yet
            if (refresh && refreshOffset < offset) {
                refreshOffset++;
                updateList(hardcore, true);
                return;
            }

            // If adapter var is null, this is the first updateList execution
            if (adapter == null) {
                adapter = new EntryAdapter(this, poeEntries, this, getResources());
                statsView.setAdapter(adapter);
            } else { // Otherwise just notify it that data has changed
                adapter.notifyDataSetChanged();
            }

            // Show a toast to the user telling them the data is updated
            showToast(hardcore ? getString(R.string.hardcore_updated) : getString(R.string.normal_updated));

            // Remove the "Load more entries" at bottom of list if we reached the maximum
            if (hardcore == showHardcore && limit + limit * offset >= max)
                statsView.removeFooterView(listFooter);
            else if (hardcore != showHardcore) {
                // Otherwise add it back if it's not there
                if (statsView.getFooterViewsCount() == 0)
                    statsView.addFooterView(listFooter);
                statsView.setSelection(0);
            }

            // Update the showHardcore var to reflect new value
            showHardcore = hardcore;

            // Update title to new mode
            setTitle(showHardcore ? R.string.hardcore : R.string.normal);

            // Invalidate the options menu to update the text properly
            // (This is only needed and supported on SDK level >= 11, since older versions
            // always update the menu every time it's shown
            if (Build.VERSION.SDK_INT >= 11)
                invalidateOptionsMenu();
        } else {
            showToast(getString(R.string.retrieve_data_fail));
        }
    } catch (JSONException e) { // Invalid JSON returned
        showToast(getString(R.string.json_parse_error));
    } catch (ClassCastException e) { // Usually indicative of a JSON parsing error
        showToast(getString(R.string.retrieve_data_fail));
    }

    hideProgress();
}

From source file:com.wso2telco.dep.mediator.ResponseHandler.java

/**
 * Make query sms status response.//from   w  w w  . jav  a2  s  .  c om
 *
 * @param mc
 *            the mc
 * @param senderAddress
 *            the sender address
 * @param requestid
 *            the requestid
 * @param responseMap
 *            the response map
 * @return the string
 */
public String makeQuerySmsStatusResponse(MessageContext mc, String senderAddress, String requestid,
        Map<String, QuerySMSStatusResponse> responseMap) {
    log.info("Building Query SMS Status Response" + " Request ID: " + UID.getRequestID(mc));
    Gson gson = new GsonBuilder().create();
    QuerySMSStatusResponse finalResponse = new QuerySMSStatusResponse();

    DeliveryInfoList deliveryInfoListObj = new DeliveryInfoList();
    List<DeliveryInfo> deliveryInfoList = new ArrayList<DeliveryInfo>(responseMap.size());

    for (Map.Entry<String, QuerySMSStatusResponse> entry : responseMap.entrySet()) {
        QuerySMSStatusResponse statusResponse = entry.getValue();
        if (statusResponse != null) {
            DeliveryInfo[] resDeliveryInfos = statusResponse.getDeliveryInfoList().getDeliveryInfo();
            Collections.addAll(deliveryInfoList, resDeliveryInfos);
        } else {
            DeliveryInfo deliveryInfo = new DeliveryInfo();
            deliveryInfo.setAddress(entry.getKey());
            deliveryInfo.setDeliveryStatus("DeliveryImpossible");
            deliveryInfoList.add(deliveryInfo);
        }
    }
    deliveryInfoListObj.setDeliveryInfo(deliveryInfoList.toArray(new DeliveryInfo[deliveryInfoList.size()]));
    try {
        senderAddress = URLEncoder.encode(senderAddress, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        log.error(e.getMessage(), e);
    }
    String resourceURL = getResourceURL(mc, senderAddress) + "/requests/" + requestid + "/deliveryInfos";
    deliveryInfoListObj.setResourceURL(resourceURL);

    finalResponse.setDeliveryInfoList(deliveryInfoListObj);

    ((Axis2MessageContext) mc).getAxis2MessageContext().setProperty("HTTP_SC", 200);
    ((Axis2MessageContext) mc).getAxis2MessageContext().setProperty("messageType", "application/json");
    return gson.toJson(finalResponse);
}

From source file:net.dv8tion.jda.core.JDABuilder.java

/**
 * Adds all provided listeners to the list of listeners that will be used to populate the {@link net.dv8tion.jda.core.JDA} object.
 * This uses the {@link net.dv8tion.jda.core.hooks.InterfacedEventManager InterfacedEventListener} by default.
 * To switch to the {@link net.dv8tion.jda.core.hooks.AnnotatedEventManager AnnotatedEventManager},
 * use {@link #setEventManager(net.dv8tion.jda.core.hooks.IEventManager) setEventManager(new AnnotatedEventManager())}.
 *
 * Note: when using the {@link net.dv8tion.jda.core.hooks.InterfacedEventManager InterfacedEventListener} (default),
 * given listener <b>must</b> be instance of {@link net.dv8tion.jda.core.hooks.EventListener EventListener}!
 *
 * @param listeners/*w w  w.ja va 2  s. c o  m*/
 *          The listeners to add to the list.
 * @return
 *      Returns the {@link net.dv8tion.jda.core.JDABuilder JDABuilder} instance. Useful for chaining.
 */
public JDABuilder addListener(Object... listeners) {
    Collections.addAll(this.listeners, listeners);
    return this;
}

From source file:io.restassured.module.mockmvc.RestAssuredMockMvc.java

/**
 * Assign one or more {@link org.springframework.test.web.servlet.ResultHandler} that'll be executes after a request has been made.
 * <p>//from  ww w.  j  a v  a 2 s  .  c  o m
 * Note that it's recommended to use {@link #with(RequestPostProcessor, RequestPostProcessor...)} instead of this method when setting
 * authentication/authorization based RequestPostProcessors.
 * </p>
 *
 * @param postProcessor            a post-processor to add
 * @param additionalPostProcessors Additional post-processors to add
 * @see MockMvcRequestSpecification#postProcessors(RequestPostProcessor, RequestPostProcessor...)
 */
public static void postProcessors(RequestPostProcessor postProcessor,
        RequestPostProcessor... additionalPostProcessors) {
    notNull(postProcessor, RequestPostProcessor.class);
    RestAssuredMockMvc.requestPostProcessors.add(postProcessor);
    if (additionalPostProcessors != null && additionalPostProcessors.length >= 1) {
        Collections.addAll(RestAssuredMockMvc.requestPostProcessors, additionalPostProcessors);
    }
}

From source file:com.example.app.profile.ui.user.UserManagement.java

private void addConstraints(SearchModelImpl searchModel) {

    searchModel.getConstraints().add(new ComboBoxConstraint() {

        private ComboBox _constraintComponent;

        @Override/*from  www. ja  v  a2 s  .c  o m*/
        public void addCriteria(QLBuilder builder,
                net.proteusframework.ui.miwt.component.Component constraintComponent) {
            ComboBox combo = (ComboBox) constraintComponent;
            MembershipType memType = (MembershipType) combo.getSelectedObject();
            if (memType != null && shouldReturnConstraintForValue(memType)) {
                QLBuilder membershipBuilder = _profileDAO.getMembershipQLBuilder();
                membershipBuilder.setProjection(
                        "distinct " + membershipBuilder.getAlias() + '.' + Membership.USER_PROP + ".id");
                membershipBuilder.appendCriteria(Membership.MEMBERSHIP_TYPE_PROP, getOperator(), memType);
                membershipBuilder.appendCriteria(Membership.PROFILE_PROP, Operator.eq, _userProfile);
                List<Integer> userIDs = membershipBuilder.getQueryResolver().list();
                if (userIDs.isEmpty())
                    userIDs.add(0);
                builder.appendCriteria(builder.getAlias() + ".id in (:usersWithRole)")
                        .putParameter("usersWithRole", userIDs);
            }
        }

        @Override
        public net.proteusframework.ui.miwt.component.Component getConstraintComponent() {
            if (_constraintComponent == null || _constraintComponent.isClosed()) {
                List<MembershipType> memTypes = new ArrayList<>();
                memTypes.add(null);
                memTypes.addAll(_profileDAO.getMembershipTypesForProfile(_userProfile));

                _constraintComponent = new ComboBox(new SimpleListModel<>(memTypes));
                _constraintComponent.setCellRenderer(new CustomCellRenderer(CommonButtonText.ANY));
            }
            return _constraintComponent;
        }
    }.withLabel(CONSTRAINT_ROLE()).withOperator(Operator.eq));

    searchModel.getConstraints().add(new SimpleConstraint("first-name").withLabel(CommonColumnText.FIRST_NAME)
            .withProperty(User.PRINCIPAL_PROP + ".contact.name.first").withOperator(Operator.like));

    searchModel.getConstraints().add(new SimpleConstraint("last-name").withLabel(CommonColumnText.LAST_NAME)
            .withProperty(User.PRINCIPAL_PROP + ".contact.name.last").withOperator(Operator.like));

    searchModel.getConstraints().add(new SimpleConstraint("username").withLabel(CommonColumnText.EMAIL)
            .withProperty(User.PRINCIPAL_PROP + ".credentials.username").withOperator(Operator.like));

    searchModel.getConstraints()
            .add(new UserPositionConstraint().withLabel(CommonColumnText.TITLE).withOperator(Operator.like));

    List<PrincipalStatus> statuses = new ArrayList<>();
    statuses.add(null);
    Collections.addAll(statuses, PrincipalStatus.values());
    searchModel.getConstraints()
            .add(new ComboBoxConstraint(statuses, PrincipalStatus.active, CommonButtonText.ANY)
                    .withLabel(CommonColumnText.STATUS).withProperty(User.PRINCIPAL_PROP + ".status")
                    .withOperator(Operator.eq));
}

From source file:net.firejack.platform.core.config.meta.construct.ConfigElementFactory.java

/**
 * @param parentEntity//from   www. j ava  2  s .  c  o  m
 * @param name
 * @param type
 * @param required
 * @param defaultValue
 * @return
 */
public IFieldElement produceField(IEntityElement parentEntity, String name, FieldType type, Boolean required,
        Object defaultValue) {
    if (parentEntity == null) {
        throw new IllegalArgumentException("Field-holder domain object should not be null.");
    } else if (!(parentEntity instanceof EntityConfigElement)) {
        throw new IllegalArgumentException("Inconsistent parent domain object argument.");
    } else if (StringUtils.isBlank(name)) {
        throw new IllegalArgumentException("The name of field should not be blank.");
    } else if (type == null) {
        throw new IllegalArgumentException("The type of field should not be null.");
    }

    IFieldElement[] fields = parentEntity.getFields();
    if (fields != null) {
        IFieldElement field = DiffUtils.findNamedElement(fields, name);
        if (field != null) {
            return field;//field already exists
        }
    }

    FieldConfigElement fieldConfigElement = produceField(name, type, required, defaultValue);

    List<IFieldElement> fieldsList = new ArrayList<IFieldElement>();
    if (fields != null) {
        Collections.addAll(fieldsList, parentEntity.getFields());
    }
    fieldsList.add(fieldConfigElement);
    EntityConfigElement domainObject = (EntityConfigElement) parentEntity;
    domainObject.setFields(fieldsList);

    return fieldConfigElement;
}