Example usage for java.util ArrayList set

List of usage examples for java.util ArrayList set

Introduction

In this page you can find the example usage for java.util ArrayList set.

Prototype

public E set(int index, E element) 

Source Link

Document

Replaces the element at the specified position in this list with the specified element.

Usage

From source file:com.krawler.spring.crm.dashboard.CrmDashboardController.java

private ArrayList getBubbleSortList(ArrayList lis) throws ServiceException, JSONException {
    for (int x = 1; x < lis.size(); x++) {
        for (int i = 0; i < lis.size() - x; i++) {
            JSONObject jobj = new JSONObject(lis.get(i).toString());
            String reportname = jobj.get("name").toString().toLowerCase();
            JSONObject jobj1 = new JSONObject(lis.get(i + 1).toString());
            String reportname1 = jobj1.get("name").toString().toLowerCase();
            if (reportname.compareToIgnoreCase(reportname1) > 0) {
                Object temp = lis.get(i);
                lis.set(i, lis.get(i + 1));
                lis.set(i + 1, temp);//from  w  w w  .ja v a2 s  . c  o  m
            }
        }
    }
    return lis;
}

From source file:grupob.TipoProceso.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

    DefaultTableModel modelo = (DefaultTableModel) jTableDistritos.getModel();
    ArrayList<Distrito> listaDistritosPas = listaDistritos;
    for (int i = 0; i < listaDistritosPas.size(); i++) {
        String a = modelo.getValueAt(i, 1).toString();
        String n = modelo.getValueAt(i, 0).toString();
        int num = -1;
        try {/*  w  w w  .  j  av a  2  s .  co m*/
            num = Integer.parseInt(a);
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(null,
                    "Error: Ingreso un valor distinto de un numero en la fila: " + (i + 1) + " columna: 2");
            return;
        }
        if (num < 0) {
            JOptionPane.showMessageDialog(null,
                    "Error: Ingreso un numero negativo en la fila: " + (i + 1) + " columna: 2");
            return;
        }
        Distrito s = listaDistritosPas.get(i);
        String co = modelo.getValueAt(i, 2).toString();
        ArrayList<Region> reg = Manager.queryByNameRegion(co);
        Distrito r = new Distrito(s.getId(), reg.get(0).getId(), n, num);
        listaDistritosPas.set(i, r);

    }
    for (int i = 0; i < listaDistritosPas.size(); i++) {
        Distrito rd = listaDistritosPas.get(i);
        if (rd.getId() != 0) {
            Manager.updateDistrito(rd);
        }
    }
    JOptionPane.showMessageDialog(null, "Se Completo de actualizar los distritos");
}

From source file:info.varden.anatychia.Main.java

public static MaterialDataList materialList(SaveData save, ProgressUpdater pu, MaterialData[] filters) {
    Random random = new Random();
    boolean filtersNull = filters == null;
    pu.updated(0, 1);// w  w w.  j  a  va2 s  . c o m
    pu.updated(-3, 1);
    MaterialDataList mdl = new MaterialDataList();
    File saveDir = save.getLocation();
    File[] regionFolders = listRegionContainers(saveDir);
    int depth = Integer.MAX_VALUE;
    File shallowest = null;
    for (File f : regionFolders) {
        String path = f.getAbsolutePath();
        Pattern p = Pattern.compile(Pattern.quote(File.separator));
        Matcher m = p.matcher(path);
        int count = 0;
        while (m.find()) {
            count++;
        }
        if (count < depth) {
            depth = count;
            if (shallowest == null || f.getName().equalsIgnoreCase("region")) {
                shallowest = f;
            }
        }
    }
    pu.updated(-1, 1);
    ArrayList<File> regions = new ArrayList<File>();
    int tfs = 0;
    for (File f : regionFolders) {
        String dimName = f.getParentFile().getName();
        boolean deleted = false;
        if (f.equals(shallowest)) {
            dimName = "DIM0";
        }
        if (!filtersNull) {
            for (MaterialData type : filters) {
                if (type.getType() == MaterialType.DIMENSION && type.getName().equals(dimName)) {
                    System.out.println("Deleting: " + dimName);
                    deleted = recursiveDelete(f);
                }
            }
        }
        if (deleted)
            continue;
        mdl.increment(new MaterialData(MaterialType.DIMENSION, dimName, 1L));
        File[] r = f.listFiles(new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith(".mca");
            }

        });
        int max = r.length;
        int cur = 0;
        for (File valid : r) {
            cur++;
            try {
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream(valid));
                byte[] offsetHeader = new byte[4096];
                bis.read(offsetHeader, 0, 4096);
                bis.close();
                ByteBuffer bb = ByteBuffer.wrap(offsetHeader);
                IntBuffer ib = bb.asIntBuffer();
                while (ib.remaining() > 0) {
                    if (ib.get() != 0) {
                        tfs++;
                    }
                }
                bb = null;
                ib = null;
            } catch (IOException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
            // tfs += Math.floor(valid.length() / 1000D);
            pu.updated(cur, max);
        }
        regions.addAll(Arrays.asList(r));
    }
    if (regions.size() <= 0) {
        pu.updated(1, 1);
        return mdl;
    }
    pu.updated(-2, 1);
    int fc = 0;
    int fs = 0;
    for (File region : regions) {
        fc++;
        //fs += Math.floor(region.length() / 1000D);
        try {
            RegionFile anvil = new RegionFile(region);
            for (int x = 0; x < 32; x++) {
                for (int z = 0; z < 32; z++) {
                    InputStream is = anvil.getChunkDataInputStream(x, z);
                    if (is == null)
                        continue;
                    NBTInputStream nbti = new NBTInputStream(is, CompressionMode.NONE);
                    CompoundTag root = (CompoundTag) nbti.readTag();
                    String rootName = root.getName();
                    CompoundTag level = (CompoundTag) root.getValue().get("Level");
                    Map<String, Tag> levelTags = level.getValue();
                    ListTag sectionTag = (ListTag) levelTags.get("Sections");
                    ArrayList<Tag> sections = new ArrayList<Tag>(sectionTag.getValue());
                    for (int i = 0; i < sections.size(); i++) {
                        mdl.setSectorsRelative(1);
                        CompoundTag sect = (CompoundTag) sections.get(i);
                        Map<String, Tag> sectTags = sect.getValue();
                        ByteArrayTag blockArray = (ByteArrayTag) sectTags.get("Blocks");
                        byte[] add = new byte[0];
                        boolean hasAdd = false;
                        if (sectTags.containsKey("Add")) {
                            hasAdd = true;
                            ByteArrayTag addArray = (ByteArrayTag) sectTags.get("Add");
                            add = addArray.getValue();
                        }
                        byte[] blocks = blockArray.getValue();
                        for (int j = 0; j < blocks.length; j++) {
                            short id;
                            byte aid = (byte) 0;
                            if (hasAdd) {
                                aid = ChunkFormat.Nibble4(add, j);
                                id = (short) ((blocks[j] & 0xFF) + (aid << 8));
                            } else {
                                id = (short) (blocks[j] & 0xFF);
                            }
                            if (!filtersNull) {
                                for (MaterialData type : filters) {
                                    if (type.getType() == MaterialType.BLOCK
                                            && type.getName().equals(String.valueOf(blocks[j] & 0xFF))
                                            && (type.getRemovalChance() == 1D
                                                    || random.nextDouble() < type.getRemovalChance())) {
                                        blocks[j] = (byte) 0;
                                        if (aid != 0) {
                                            add[j / 2] = (byte) (add[j / 2] & (j % 2 == 0 ? 0xF0 : 0x0F));
                                        }
                                        id = (short) 0;
                                    }
                                }
                            }
                            mdl.increment(new MaterialData(MaterialType.BLOCK, String.valueOf(id), 1L));
                        }
                        if (!filtersNull) {
                            HashMap<String, Tag> rSectTags = new HashMap<String, Tag>();
                            rSectTags.putAll(sectTags);
                            ByteArrayTag bat = new ByteArrayTag("Blocks", blocks);
                            rSectTags.put("Blocks", bat);
                            if (hasAdd) {
                                ByteArrayTag adt = new ByteArrayTag("Add", add);
                                rSectTags.put("Add", adt);
                            }
                            CompoundTag rSect = new CompoundTag(sect.getName(), rSectTags);
                            sections.set(i, rSect);
                        }
                    }
                    ListTag entitiesTag = (ListTag) levelTags.get("Entities");
                    ArrayList<Tag> entities = new ArrayList<Tag>(entitiesTag.getValue());
                    for (int i = entities.size() - 1; i >= 0; i--) {
                        CompoundTag entity = (CompoundTag) entities.get(i);
                        Map<String, Tag> entityTags = entity.getValue();
                        if (entityTags.containsKey("id")) {
                            StringTag idTag = (StringTag) entityTags.get("id");
                            String id = idTag.getValue();
                            boolean removed = false;
                            if (!filtersNull) {
                                for (MaterialData type : filters) {
                                    if (type.getType() == MaterialType.ENTITY
                                            && (type.getName().equals(id) || type.getName().equals(""))
                                            && (type.getRemovalChance() == 1D
                                                    || random.nextDouble() < type.getRemovalChance())) {
                                        if (type.fulfillsRequirements(entity)) {
                                            entities.remove(i);
                                            removed = true;
                                        }
                                    }
                                }
                            }
                            if (!removed) {
                                mdl.increment(new MaterialData(MaterialType.ENTITY, id, 1L));
                            }
                        }
                    }
                    nbti.close();
                    is.close();
                    if (!filtersNull) {
                        HashMap<String, Tag> rLevelTags = new HashMap<String, Tag>();
                        rLevelTags.putAll(levelTags);
                        ListTag rSectionTag = new ListTag("Sections", CompoundTag.class, sections);
                        rLevelTags.put("Sections", rSectionTag);
                        ListTag rEntityTag = new ListTag("Entities", CompoundTag.class, entities);
                        rLevelTags.put("Entities", rEntityTag);
                        final CompoundTag rLevel = new CompoundTag("Level", rLevelTags);
                        HashMap<String, Tag> rRootTags = new HashMap<String, Tag>() {
                            {
                                put("Level", rLevel);
                            }
                        };
                        CompoundTag rRoot = new CompoundTag(rootName, rRootTags);
                        OutputStream os = anvil.getChunkDataOutputStream(x, z);
                        NBTOutputStream nbto = new NBTOutputStream(os, CompressionMode.NONE);
                        nbto.writeTag(rRoot);
                        nbto.close();
                    }
                    fs++;
                    pu.updated(fs, tfs);
                }
            }
            anvil.close();
        } catch (Exception ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    MaterialData[] data = mdl.toArray();
    System.out.println("FILES SCANNED: " + fc);
    for (MaterialData d : data) {
        System.out.println(d.getType().getName() + ": " + d.getName() + " (" + d.getQuantity() + ")");
    }
    return mdl;
}

From source file:com.globalsight.everest.webapp.pagehandler.tasks.TaskDetailHandler.java

private void downloadSourcePages(HttpServletRequest p_request, HttpServletResponse p_response, Task p_task)
        throws IOException {
    HttpSession session = p_request.getSession(false);
    List sourcePages = (List) p_task.getSourcePages();

    Iterator it = sourcePages.iterator();
    String m_cxeDocsDir = SystemConfiguration.getInstance()
            .getStringParameter(SystemConfigParamNames.CXE_DOCS_DIR, String.valueOf(p_task.getCompanyId()));
    ArrayList<String> fileNames = new ArrayList<String>();
    ArrayList<String> filePaths = new ArrayList<String>();
    Map<String, String> mapOfNamePath = new HashMap<String, String>();
    while (it.hasNext()) {
        SourcePage sourcePage = (SourcePage) it.next();

        if (sourcePage.hasRemoved()) {
            continue;
        }//from   w  ww.  j  av  a  2s .  c om

        StringBuffer sourceSb = new StringBuffer().append(m_cxeDocsDir).append("/");
        String externalPageId = sourcePage.getExternalPageId();
        externalPageId = externalPageId.replace("\\", "/");

        if (PassoloUtil.isPassoloFile(sourcePage)) {
            externalPageId = externalPageId.substring(0, externalPageId.lastIndexOf(".lpu/") + 4);
        }

        externalPageId = SourcePage.filtSpecialFile(externalPageId);

        if (filePaths.contains(externalPageId))
            continue;

        sourceSb = sourceSb.append(externalPageId);
        filePaths.add(externalPageId);
        fileNames.add(sourceSb.toString());
        mapOfNamePath.put(sourceSb.toString(), externalPageId);
    }
    Map<String, String> entryNamesMap = new HashMap<String, String>();
    String jobName = p_task.getJobName();
    String zipFileName = URLEncoder.encode(jobName + ".zip");
    File tmpFile = File.createTempFile("GSDownloadSource", ".zip");
    try {
        JobPackageZipper m_zipper = new JobPackageZipper();
        m_zipper.createZipFile(tmpFile);
        entryNamesMap = ZipIt.getEntryNamesMap(filePaths);
        for (int i = 0; i < fileNames.size(); i++) {
            filePaths.set(i, entryNamesMap.get(mapOfNamePath.get(fileNames.get(i))));
        }
        addSourcePages(m_zipper, fileNames, filePaths, zipFileName);
        m_zipper.closeZipFile();
        CommentFilesDownLoad commentFilesDownload = new CommentFilesDownLoad();
        commentFilesDownload.sendFileToClient(p_request, p_response, jobName + ".zip", tmpFile);
    } finally {
        FileUtil.deleteTempFile(tmpFile);
    }
}

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   ww  w  . ja  v  a  2s.co 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:im.vector.adapters.VectorRoomSummaryAdapter.java

/**
 * Build an array of RoomSummary objects organized according to the room tags (sections).
 * So far we have 4 sections/*from   www.  ja v a 2s  . co m*/
 * - the invited rooms
 * - the rooms with tags ROOM_TAG_FAVOURITE
 * - the rooms with tags ROOM_TAG_LOW_PRIORITY
 * - the rooms with tags ROOM_TAG_NO_TAG (displayed as "ROOMS")
 * The section indexes: mFavouriteSectionIndex, mNoTagSectionIndex and mFavouriteSectionIndex are
 * also computed in this method.
 *
 * @param aRoomSummaryCollection the complete list of RoomSummary objects
 * @return an array of summary lists splitted by sections
 */
private ArrayList<ArrayList<RoomSummary>> buildSummariesByGroups(
        final Collection<RoomSummary> aRoomSummaryCollection) {
    ArrayList<ArrayList<RoomSummary>> summaryListByGroupsRetValue = new ArrayList<>();
    String roomSummaryId;

    // init index with default values
    mRoomByAliasGroupPosition = -1;
    mDirectoryGroupPosition = -1;
    mInvitedGroupPosition = -1;
    mFavouritesGroupPosition = -1;
    mNoTagGroupPosition = -1;
    mLowPriorGroupPosition = -1;

    if (null != aRoomSummaryCollection) {

        RoomSummary dummyRoomSummary = new RoomSummary();

        // Retrieve lists of room IDs(strings) according to their tags
        final List<String> favouriteRoomIdList = mMxSession.roomIdsWithTag(RoomTag.ROOM_TAG_FAVOURITE);
        final List<String> lowPriorityRoomIdList = mMxSession.roomIdsWithTag(RoomTag.ROOM_TAG_LOW_PRIORITY);

        // ArrayLists allocations: will contain the RoomSummary objects deduced from roomIdsWithTag()
        ArrayList<RoomSummary> inviteRoomSummaryList = new ArrayList<>();
        ArrayList<RoomSummary> favouriteRoomSummaryList = new ArrayList<>(favouriteRoomIdList.size());
        ArrayList<RoomSummary> lowPriorityRoomSummaryList = new ArrayList<>();
        ArrayList<RoomSummary> noTagRoomSummaryList = new ArrayList<>(lowPriorityRoomIdList.size());

        fillList(favouriteRoomSummaryList, dummyRoomSummary, favouriteRoomIdList.size());
        fillList(lowPriorityRoomSummaryList, dummyRoomSummary, lowPriorityRoomIdList.size());

        // Search loop going through all the summaries:
        // here we translate the roomIds (Strings) to their corresponding RoomSummary objects
        for (RoomSummary roomSummary : aRoomSummaryCollection) {
            roomSummaryId = roomSummary.getRoomId();
            Room room = mMxSession.getDataHandler().getStore().getRoom(roomSummaryId);

            // check if the room exists
            // the user conference rooms are not displayed.
            if ((null != room) && isMatchedPattern(room) && !room.isConferenceUserRoom()) {
                // list first the summary
                if (room.isInvited()) {
                    inviteRoomSummaryList.add(roomSummary);
                } else {
                    int pos;

                    // search for each room Id in the room Id lists, retrieved from their corresponding tags
                    pos = favouriteRoomIdList.indexOf(roomSummaryId);
                    if (pos >= 0) {
                        // update the favourites list
                        // the favorites are ordered
                        favouriteRoomSummaryList.set(pos, roomSummary);
                    } else if ((pos = lowPriorityRoomIdList.indexOf(roomSummaryId)) >= 0) {
                        // update the low priority list
                        // the low priority are ordered
                        lowPriorityRoomSummaryList.set(pos, roomSummary);
                    } else {
                        // default case: update the no tag list
                        noTagRoomSummaryList.add(roomSummary);
                    }
                }
            } else if (null == room) {
                Log.e(DBG_CLASS_NAME, "buildSummariesBySections " + roomSummaryId + " has no known room");
            }
        }

        // Adding sections
        // Note the order here below: first the "invitations",  "favourite", then "no tag" and then "low priority"
        int groupIndex = 0;

        // in search mode
        // the public rooms have a dedicated section
        if (mIsSearchMode || mDisplayDirectoryGroupWhenEmpty || mForceDirectoryGroupDisplay) {

            // detect if the pattern might a room ID or an alias
            if (!TextUtils.isEmpty(mSearchedPattern)) {
                // a room id is !XXX:server.ext
                // a room alias is #XXX:server.ext

                boolean isRoomId = false;
                boolean isRoomAlias = false;

                if (mSearchedPattern.startsWith("!")) {
                    int sep = mSearchedPattern.indexOf(":");

                    if (sep > 0) {
                        sep = mSearchedPattern.indexOf(".", sep);
                    }

                    isRoomId = sep > 0;
                } else if (mSearchedPattern.startsWith("#")) {
                    int sep = mSearchedPattern.indexOf(":");

                    if (sep > 0) {
                        sep = mSearchedPattern.indexOf(".", sep);
                    }

                    isRoomAlias = sep > 0;
                }

                if (isRoomId || isRoomAlias) {
                    mRoomByAliasGroupPosition = groupIndex++;
                }
            }

            mDirectoryGroupPosition = groupIndex++;
            // create a dummy entry to keep match between section index <-> summaries list
            summaryListByGroupsRetValue.add(new ArrayList<RoomSummary>());
        }

        // first the invitations
        if (0 != inviteRoomSummaryList.size()) {
            // the invitations are sorted from the older to the oldest to the more recent ones
            Collections.reverse(inviteRoomSummaryList);
            summaryListByGroupsRetValue.add(inviteRoomSummaryList);
            mInvitedGroupPosition = groupIndex;
            groupIndex++;
        }

        // favourite
        while (favouriteRoomSummaryList.remove(dummyRoomSummary))
            ;
        if (0 != favouriteRoomSummaryList.size()) {
            summaryListByGroupsRetValue.add(favouriteRoomSummaryList);
            mFavouritesGroupPosition = groupIndex; // save section index
            groupIndex++;
        }

        // no tag
        if (0 != noTagRoomSummaryList.size()) {
            summaryListByGroupsRetValue.add(noTagRoomSummaryList);
            mNoTagGroupPosition = groupIndex; // save section index
            groupIndex++;
        }

        // low priority
        while (lowPriorityRoomSummaryList.remove(dummyRoomSummary))
            ;
        if (0 != lowPriorityRoomSummaryList.size()) {
            summaryListByGroupsRetValue.add(lowPriorityRoomSummaryList);
            mLowPriorGroupPosition = groupIndex; // save section index
            groupIndex++;
        }

        // in avoiding empty history mode
        // check if there is really nothing else
        if (mDisplayDirectoryGroupWhenEmpty && !mForceDirectoryGroupDisplay && (groupIndex > 1)) {
            summaryListByGroupsRetValue.remove(mDirectoryGroupPosition);
            mRoomByAliasGroupPosition = -1;
            mDirectoryGroupPosition = -1;
            mInvitedGroupPosition--;
            mFavouritesGroupPosition--;
            mNoTagGroupPosition--;
            mLowPriorGroupPosition--;
        }
    }

    return summaryListByGroupsRetValue;
}

From source file:org.apache.tajo.engine.parser.HiveQLAnalyzer.java

@Override
public Aggregation visitGroupByClause(HiveQLParser.GroupByClauseContext ctx) {
    Aggregation clause = new Aggregation();

    if (ctx.groupByExpression().size() > 0) {
        int elementSize = ctx.groupByExpression().size();
        ArrayList<Aggregation.GroupElement> groups = new ArrayList<Aggregation.GroupElement>(elementSize + 1);
        ArrayList<Expr> ordinaryExprs = new ArrayList<Expr>();
        int groupSize = 1;
        groups.add(null);/*from ww w  .j  av a  2 s  . c o  m*/

        for (int i = 0; i < ctx.groupByExpression().size(); i++) {
            Expr expr = visitGroupByExpression(ctx.groupByExpression(i));

            if (expr instanceof FunctionExpr) {
                FunctionExpr function = (FunctionExpr) expr;

                if (function.getSignature().equalsIgnoreCase("ROLLUP")) {
                    groupSize++;
                    groups.add(
                            new Aggregation.GroupElement(Aggregation.GroupType.Rollup, function.getParams()));
                } else if (function.getSignature().equalsIgnoreCase("CUBE")) {
                    groupSize++;
                    groups.add(new Aggregation.GroupElement(Aggregation.GroupType.Cube, function.getParams()));
                } else {
                    Collections.addAll(ordinaryExprs, function);
                }
            } else {
                Collections.addAll(ordinaryExprs, (ColumnReferenceExpr) expr);
            }
        }

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

    //TODO: grouping set expression
    return clause;
}

From source file:org.akaza.openclinica.control.managestudy.UpdateStudyEventServlet.java

private void populateUncompletedCRFsWithCRFAndVersions(ArrayList uncompletedEventDefinitionCRFs) {
    CRFDAO cdao = new CRFDAO(sm.getDataSource());
    CRFVersionDAO cvdao = new CRFVersionDAO(sm.getDataSource());

    int size = uncompletedEventDefinitionCRFs.size();
    for (int i = 0; i < size; i++) {
        DisplayEventDefinitionCRFBean dedcrf = (DisplayEventDefinitionCRFBean) uncompletedEventDefinitionCRFs
                .get(i);//w w  w.j a va2s. c  om
        CRFBean cb = (CRFBean) cdao.findByPK(dedcrf.getEdc().getCrfId());
        // note that we do not check status in the above query, so let's
        // check it here, tbh 102007
        if (cb.getStatus().equals(Status.AVAILABLE)) {
            // the above does not allow us to show the CRF as a thing with
            // status of 'invalid' so we have to
            // go to the JSP for this one, I think
            dedcrf.getEdc().setCrf(cb);

            ArrayList versions = (ArrayList) cvdao.findAllActiveByCRF(dedcrf.getEdc().getCrfId());
            dedcrf.getEdc().setVersions(versions);
            // added tbh 092007, fix for 1461
            if (versions != null && versions.size() != 0) {
                boolean isLocked = false;
                for (int ii = 0; ii < versions.size(); ii++) {
                    CRFVersionBean crfvb = (CRFVersionBean) versions.get(ii);
                    logger.debug("...checking versions..." + crfvb.getName());
                    if (!crfvb.getStatus().equals(Status.AVAILABLE)) {
                        logger.debug("found a non active crf version");
                        isLocked = true;
                    }
                }
                logger.debug("re-set event def, line 240: " + isLocked);
                if (isLocked) {
                    dedcrf.setStatus(Status.LOCKED);
                    dedcrf.getEventCRF().setStage(DataEntryStage.LOCKED);
                }
                uncompletedEventDefinitionCRFs.set(i, dedcrf);
            } else {// above added 092007, tbh
                dedcrf.setStatus(Status.LOCKED);
                dedcrf.getEventCRF().setStage(DataEntryStage.LOCKED);
                uncompletedEventDefinitionCRFs.set(i, dedcrf);
            } // added 102007, tbh
        } else {
            dedcrf.getEdc().setCrf(cb);
            logger.debug("_found a non active crf _");
            dedcrf.setStatus(Status.LOCKED);
            dedcrf.getEventCRF().setStage(DataEntryStage.LOCKED);
            dedcrf.getEdc().getCrf().setStatus(Status.LOCKED);
            uncompletedEventDefinitionCRFs.set(i, dedcrf);
        } // enclosing if statement added 102007, tbh
    }
}

From source file:com.photon.maven.plugins.android.phase09package.ApkMojo.java

/**
 * Creates the APK file using the internal APKBuilder.
 *
 * @param outputFile//from   www.j a v a 2 s.  co m
 *            the output file
 * @param dexFile
 *            the dex file
 * @param zipArchive
 *            the classes folder
 * @param sourceFolders
 *            the resources
 * @param jarFiles
 *            the embedded java files
 * @param nativeFolders
 *            the native folders
 * @param verbose
 *            enables the verbose mode
 * @param signWithDebugKeyStore
 *            enables the signature of the APK using the debug key
 * @param debug
 *            enables the debug mode
 * @throws MojoExecutionException
 *             if the APK cannot be created.
 */
private void doAPKWithAPKBuilder(File outputFile, File dexFile, File zipArchive, ArrayList<File> sourceFolders,
        ArrayList<File> jarFiles, ArrayList<File> nativeFolders, boolean verbose, boolean signWithDebugKeyStore,
        boolean debug) throws MojoExecutionException {

    /* Following line doesn't make any difference if we keep it or comment it
     * Commented By - Viral - Feb 11, 2012
     */
    //      sourceFolders.add(new File(project.getBuild().getDirectory(), "android-classes"));

    for (Artifact artifact : getRelevantCompileArtifacts()) {
        if (extractDuplicates) {
            try {
                computeDuplicateFiles(artifact.getFile());
            } catch (Exception e) {
                getLog().warn("Cannot compute duplicates files from " + artifact.getFile().getAbsolutePath(),
                        e);
            }
        }
        jarFiles.add(artifact.getFile());
    }

    // Check duplicates.
    if (extractDuplicates) {
        List<String> duplicates = new ArrayList<String>();
        List<File> jarToModify = new ArrayList<File>();
        for (String s : m_jars.keySet()) {
            List<File> l = m_jars.get(s);
            if (l.size() > 1) {
                getLog().warn("Duplicate file " + s + " : " + l);
                duplicates.add(s);
                for (int i = 1; i < l.size(); i++) {
                    if (!jarToModify.contains(l.get(i))) {
                        jarToModify.add(l.get(i));
                    }
                }
            }
        }

        // Rebuild jars.
        for (File file : jarToModify) {
            File newJar;
            newJar = removeDuplicatesFromJar(file, duplicates);
            int index = jarFiles.indexOf(file);
            if (newJar != null) {
                jarFiles.set(index, newJar);
            }

        }
    }

    ApkBuilder builder = new ApkBuilder(outputFile, zipArchive, dexFile, signWithDebugKeyStore,
            (verbose) ? System.out : null);

    if (debug) {
        builder.setDebugMode(debug);
    }
    /* Following code block is responsible to make the .apk size almost doubled.
     * Commented By - Viral - Feb 11, 2012
     */
    //      for (File sourceFolder : sourceFolders) {
    //         builder.addSourceFolder(sourceFolder);
    //      }

    for (File jarFile : jarFiles) {
        if (jarFile.isDirectory()) {
            String[] filenames = jarFile.list(new FilenameFilter() {
                @Override
                public boolean accept(File dir, String name) {
                    return PATTERN_JAR_EXT.matcher(name).matches();
                }
            });

            for (String filename : filenames) {
                builder.addResourcesFromJar(new File(jarFile, filename));
            }
        } else {
            builder.addResourcesFromJar(jarFile);
        }
    }

    for (File nativeFolder : nativeFolders) {
        builder.addNativeLibraries(nativeFolder, null);
    }

    builder.sealApk();
}

From source file:au.org.ala.layers.dao.LayerIntersectDAOImpl.java

ArrayList<String> remoteSampling(IntersectionFile[] intersectionFiles, double[][] points,
        IntersectCallback callback) {/*from   www  . j a  v a 2s.c o  m*/
    logger.info("begin REMOTE sampling, number of threads " + intersectConfig.getThreadCount()
            + ", number of layers=" + intersectionFiles.length + ", number of coordinates=" + points.length);

    ArrayList<String> output = null;

    try {
        long start = System.currentTimeMillis();
        URL url = new URL(intersectConfig.getLayerIndexUrl() + "/intersect/batch");
        URLConnection c = url.openConnection();
        c.setDoOutput(true);

        OutputStreamWriter out = null;
        try {
            out = new OutputStreamWriter(c.getOutputStream());
            out.write("fids=");
            for (int i = 0; i < intersectionFiles.length; i++) {
                if (i > 0) {
                    out.write(",");
                }
                out.write(intersectionFiles[i].getFieldId());
            }
            out.write("&points=");
            for (int i = 0; i < points.length; i++) {
                if (i > 0) {
                    out.write(",");
                }
                out.write(String.valueOf(points[i][1]));
                out.write(",");
                out.write(String.valueOf(points[i][0]));
            }
            out.flush();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }

        JSONObject jo = JSONObject.fromObject(IOUtils.toString(c.getInputStream()));

        String checkUrl = jo.getString("statusUrl");

        //check status
        boolean notFinished = true;
        String downloadUrl = null;
        while (notFinished) {
            //wait 5s before querying status
            Thread.sleep(5000);

            jo = JSONObject.fromObject(IOUtils.toString(new URI(checkUrl).toURL().openStream()));

            if (jo.containsKey("error")) {
                notFinished = false;
            } else if (jo.containsKey("status")) {
                String status = jo.getString("status");

                if ("finished".equals(status)) {
                    downloadUrl = jo.getString("downloadUrl");
                    notFinished = false;
                } else if ("cancelled".equals(status) || "error".equals(status)) {
                    notFinished = false;
                }
            }
        }

        ZipInputStream zis = null;
        CSVReader csv = null;
        InputStream is = null;
        ArrayList<StringBuilder> tmpOutput = new ArrayList<StringBuilder>();
        long mid = System.currentTimeMillis();
        try {
            is = new URI(downloadUrl).toURL().openStream();
            zis = new ZipInputStream(is);
            ZipEntry ze = zis.getNextEntry();
            csv = new CSVReader(new InputStreamReader(zis));

            for (int i = 0; i < intersectionFiles.length; i++) {
                tmpOutput.add(new StringBuilder());
            }
            String[] line;
            int row = 0;
            csv.readNext(); //discard header
            while ((line = csv.readNext()) != null) {
                //order is consistent with request
                for (int i = 2; i < line.length && i - 2 < tmpOutput.size(); i++) {
                    if (row > 0) {
                        tmpOutput.get(i - 2).append("\n");
                    }
                    tmpOutput.get(i - 2).append(line[i]);
                }
                row++;
            }

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            if (zis != null) {
                try {
                    zis.close();
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
            if (csv != null) {
                try {
                    csv.close();
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }

        output = new ArrayList<String>();
        for (int i = 0; i < tmpOutput.size(); i++) {
            output.add(tmpOutput.get(i).toString());
            tmpOutput.set(i, null);
        }

        long end = System.currentTimeMillis();

        logger.info("sample time for " + 5 + " layers and " + 3 + " coordinates: get response=" + (mid - start)
                + "ms, write response=" + (end - mid) + "ms");

    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
    return output;
}