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:gov.lanl.adore.djatoka.plugin.ExtractPDF.java

/**
 * Extracts region defined in DjatokaDecodeParam as BufferedImage
 * @param input absolute file path of PDF file.
 * @param params DjatokaDecodeParam instance containing region and transform settings.
 * @return extracted region as a BufferedImage
 * @throws DjatokaException//from   w ww  .j  av a2 s.  c om
 */
@Override
public BufferedImage process(String input, DjatokaDecodeParam params) throws DjatokaException {

    logger.debug("ExtractPDF.process:\n\tinput: " + input + "\n\tparams: " + params);

    if (input == null)
        throw new DjatokaException("Unknown failure while converting file: no image produced.");

    try {
        setPDFCommandsPath();
    } catch (IllegalStateException e) {
        logger.error("Failed to set PDF commands path: ", e);
        throw e;
    }

    int page_number = 1 + params.getCompositingLayer(); // From 0-based to 1-based.
    int status = 0;
    BufferedImage processedImage = null;
    try {
        /*
        // First get max physical dim of bounding box of the page
        // to compute the DPI to ask for..  otherwise some AutoCAD
        // drawings can produce enormous files even at 75dpi, for
        // 48" drawings..
        int dpi = 0;
        Dimension pageSize = getPDFPageSize(input, page_number);
        if (pageSize == null)
        {
        logger.error("Sanity check: Did not find \"Page " + page_number + " size\" line in output of pdfinfo, file="+input);
        throw new IllegalArgumentException("Failed to get \"Page " + page_number + " size\" of PDF with pdfinfo.");
        }
        else
        {
        double w = pageSize.getWidth();
        double h = pageSize.getHeight();
        int maxdim = (int)Math.max(Math.abs(w), Math.abs(h));
        dpi = Math.min(MAX_DPI, (MAX_PX * 72 / maxdim));
        logger.debug("DPI: pdfinfo method got dpi="+dpi+" for max dim="+maxdim+" (points, 1/72\")");
        } */

        // Scale
        int dpi = getScaledDPI(params);

        // Requires Sun JAI imageio additions to read ppm directly.
        // this will get "-[0]+1.ppm" appended to it by pdftoppm
        File outPrefixF = File.createTempFile("pdftopng", "out");
        String outPrefix = outPrefixF.toString();
        outPrefixF.delete();

        //String pdfCmd[] = PDFTOPPM_COMMAND.clone();
        ArrayList<String> pdfCmd = new ArrayList<String>(Arrays.asList(PDFTOPPM_COMMAND));
        pdfCmd.set(PDFTOPPM_COMMAND_POSITION_BIN, pdftoppmPath);
        pdfCmd.set(PDFTOPPM_COMMAND_POSITION_FIRSTPAGE, "" + page_number);
        pdfCmd.set(PDFTOPPM_COMMAND_POSITION_LASTPAGE, "" + page_number);
        pdfCmd.set(PDFTOPPM_COMMAND_POSITION_DPI, String.valueOf(dpi));
        pdfCmd.set(PDFTOPPM_COMMAND_POSITION_FILE, input.toString());
        pdfCmd.set(PDFTOPPM_COMMAND_POSITION_OUTPUTFILE, outPrefix);

        // Crop
        Rectangle crop = getCropParam(params);
        if (crop != null) {
            String[] cropParams = { "-x", "" + (int) crop.getX(), "-y", "" + (int) crop.getY(), "-W",
                    "" + (int) crop.getWidth(), "-H", "" + (int) crop.getHeight() };
            pdfCmd.addAll(PDFTOPPM_COMMAND_POSITION_OPTIONAL_EXTRAS, Arrays.asList(cropParams));
        }

        String[] pdfCmdA = pdfCmd.toArray(new String[pdfCmd.size()]);
        logger.debug("Running pdftoppm command: " + Arrays.deepToString(pdfCmdA));
        //logger.debug("Running pdftoppm command: " + pdfCmd.toString());

        File outf = null;
        Process pdfProc = null;
        try {
            pdfProc = Runtime.getRuntime().exec(pdfCmdA);
            status = pdfProc.waitFor();
            logger.debug("status: " + status);

            // pdftoppm uses variable numbers of padding 0s to the output prefix.
            // E.g., may be prefix-000001.png, prefix-001.png or even prefix-01.png.
            // Version 0.12.3 (Poppler, not XPDF) seems to consider the total number of pages.
            // So, for example, in a PDF with 90 pages, the output will be "prefix-02.png";
            // for a PDF with 350 pages, the output will be "prefix-002.png".
            // FIXME: try some approach where the PDF number of pages is considered without
            // running pdfinfo command again, thus making it simpler to determine the number
            // of padding zeros. Right now we going "brute force" because we do not know if
            // it is feasable to once again run the pdfinfo command.
            String tests[] = { outPrefix + "-" + page_number + ".png", outPrefix + "-0" + page_number + ".png",
                    outPrefix + "-00" + page_number + ".png", outPrefix + "-000" + page_number + ".png",
                    outPrefix + "-0000" + page_number + ".png", outPrefix + "-00000" + page_number + ".png" };
            for (String outname : tests) {
                if ((new File(outname)).exists()) {
                    outf = new File(outname);
                    break;
                }
            }
            logger.debug("PDFTOPPM output is: " + outf + ", exists=" + outf != null ? outf.exists() : "!");
            processedImage = ImageIO.read(outf);

            // Rotate
            if (params.getRotationDegree() > 0) {
                processedImage = ImageProcessingUtils.rotate(processedImage, params.getRotationDegree());
            }
        } catch (InterruptedException e) {
            logger.error("Failed converting PDF file to image: ", e);
            throw new IllegalArgumentException("Failed converting PDF file to image: ", e);
        } finally {
            if (outf != null)
                outf.delete();
            // Our exec() should not produce any output, but we want to stay safe.
            // http://mark.koli.ch/2011/01/leaky-pipes-remember-to-close-your-streams-when-using-javas-runtimegetruntimeexec.html
            org.apache.commons.io.IOUtils.closeQuietly(pdfProc.getOutputStream());
            org.apache.commons.io.IOUtils.closeQuietly(pdfProc.getInputStream());
            org.apache.commons.io.IOUtils.closeQuietly(pdfProc.getErrorStream());
        }
    } catch (Exception e) {
        logger.error("Failed converting PDF file to image: ", e);
        throw new IllegalArgumentException("Failed converting PDF file to image: ", e);
    } finally {
        if (status != 0)
            logger.error("PDF conversion proc failed, exit status=" + status + ", file=" + input);
    }

    return processedImage;
}

From source file:org.apache.hadoop.hbase.replication.ScopeWALEntryFilter.java

@Override
public Entry filter(Entry entry) {
    NavigableMap<byte[], Integer> scopes = entry.getKey().getReplicationScopes();
    if (scopes == null || scopes.isEmpty()) {
        return null;
    }/*from w w w .  j  a v  a 2 s .  co m*/
    ArrayList<Cell> cells = entry.getEdit().getCells();
    int size = cells.size();
    byte[] fam;
    for (int i = size - 1; i >= 0; i--) {
        Cell cell = cells.get(i);
        // If a bulk load entry has a scope then that means user has enabled replication for bulk load
        // hfiles.
        // TODO There is a similar logic in TableCfWALEntryFilter but data structures are different so
        // cannot refactor into one now, can revisit and see if any way to unify them.
        if (CellUtil.matchingColumn(cell, WALEdit.METAFAMILY, WALEdit.BULK_LOAD)) {
            Cell filteredBulkLoadEntryCell = filterBulkLoadEntries(scopes, cell);
            if (filteredBulkLoadEntryCell != null) {
                cells.set(i, filteredBulkLoadEntryCell);
            } else {
                cells.remove(i);
            }
        } else {
            // The scope will be null or empty if
            // there's nothing to replicate in that WALEdit
            fam = CellUtil.cloneFamily(cell);
            if (!scopes.containsKey(fam) || scopes.get(fam) == HConstants.REPLICATION_SCOPE_LOCAL) {
                cells.remove(i);
            }
        }
    }
    if (cells.size() < size / 2) {
        cells.trimToSize();
    }
    return entry;
}

From source file:com.ibm.bi.dml.yarn.ropt.ResourceOptimizer.java

/**
 * //  w ww . j a  va 2s .c  om
 * @param inst
 * @return 
 * @throws DMLRuntimeException 
 */
private static ArrayList<Instruction> annotateMRJobInstructions(ArrayList<Instruction> inst, long cp, long mr)
        throws DMLRuntimeException {
    //check for empty instruction lists (e.g., predicates)
    if (inst == null || !COSTS_MAX_PARALLELISM)
        return inst;

    try {
        for (int i = 0; i < inst.size(); i++) {
            Instruction linst = inst.get(i);
            if (linst instanceof MRJobInstruction) {
                //copy mr job instruction
                MRJobResourceInstruction newlinst = new MRJobResourceInstruction((MRJobInstruction) linst);

                //compute and annotate
                long maxMemPerNode = (long) YarnClusterAnalyzer.getMaxAllocationBytes();
                long nNodes = YarnClusterAnalyzer.getNumNodes();
                long totalMem = nNodes * maxMemPerNode;
                long maxMRTasks = (long) (totalMem - DMLYarnClient.computeMemoryAllocation(cp))
                        / (long) DMLYarnClient.computeMemoryAllocation(mr);
                newlinst.setMaxMRTasks(maxMRTasks);

                //write enhanced instruction back
                inst.set(i, newlinst);
            }
        }
    } catch (Exception ex) {
        throw new DMLRuntimeException(ex);
    }

    return inst;
}

From source file:com.github.paradam.infinitepager.InfiniteFragmentStatePagerAdapter.java

@Override
public void notifyDataSetChanged() {
    onPreNotifyDataSetChange();// w w w  . ja v a  2s  . c o  m
    final int count = getRelativeCount();
    final int margin = getMargin();

    ArrayList<Fragment.SavedState> newSavedState = new ArrayList<Fragment.SavedState>(count);
    ArrayList<Fragment> newFragments = new ArrayList<Fragment>(count);

    int length = mFragments.size();

    for (int x = 0; x < length; x++) {
        int position = getItemPosition(mFragments.get(x));
        switch (position) {
        case POSITION_UNCHANGED:
            while (newFragments.size() < x + 1) {
                newFragments.add(null);
                newSavedState.add(null);
            }
            newFragments.set(x, mFragments.get(x));
            if (mSavedState.size() > x) {
                newSavedState.set(x, mSavedState.get(x));
            }
            break;
        case POSITION_NONE:
            // Do not add fragment.
            if (mCurTransaction == null) {
                mCurTransaction = mFragmentManager.beginTransaction();
            }
            mCurTransaction.remove(mFragments.get(x));
            break;
        default:
            position = (position - margin + count) % count;
            while (newFragments.size() < position + 1) {
                newFragments.add(null);
                newSavedState.add(null);
            }
            newFragments.set(position, mFragments.get(x));
            if (mSavedState.size() > x) {
                newSavedState.set(position, mSavedState.get(x));
            }
        }
    }

    mSavedState = newSavedState;
    mFragments = newFragments;

    super.notifyDataSetChanged();
}

From source file:com.lyft.hive.serde.DynamoDbSerDe.java

@Override
public Object deserialize(Writable blob) throws SerDeException {
    ArrayList<Object> row = buildRow();
    Text rowText = (Text) blob;
    Map<String, String> values = decomposeRow(rowText.toString());

    for (int c = 0; c < numColumns; c++) {
        try {/*from  ww  w  . ja v  a  2  s  .  c  om*/
            String t = values.get(columnNames.get(c));
            TypeInfo typeInfo = columnTypes.get(c);

            // Convert the column to the correct type when needed and set in row obj
            PrimitiveTypeInfo pti = (PrimitiveTypeInfo) typeInfo;
            switch (pti.getPrimitiveCategory()) {
            case STRING:
                row.set(c, t);
                break;
            case BYTE:
                Byte b;
                b = Byte.valueOf(t);
                row.set(c, b);
                break;
            case SHORT:
                Short s;
                s = Short.valueOf(t);
                row.set(c, s);
                break;
            case INT:
                Integer i;
                i = Integer.valueOf(t);
                row.set(c, i);
                break;
            case LONG:
                Long l;
                l = Long.valueOf(t);
                row.set(c, l);
                break;
            case FLOAT:
                Float f;
                f = Float.valueOf(t);
                row.set(c, f);
                break;
            case DOUBLE:
                Double d;
                d = Double.valueOf(t);
                row.set(c, d);
                break;
            case BOOLEAN:
                Boolean bool;
                bool = Boolean.valueOf(t);
                row.set(c, bool);
                break;
            case TIMESTAMP:
                row.set(c, parseTimestamp(t));
                break;
            case DATE:
                Date date;
                date = Date.valueOf(t);
                row.set(c, date);
                break;
            case DECIMAL:
                HiveDecimal bd = HiveDecimal.create(t);
                row.set(c, bd);
                break;
            case CHAR:
                HiveChar hc = new HiveChar(t, ((CharTypeInfo) typeInfo).getLength());
                row.set(c, hc);
                break;
            case VARCHAR:
                HiveVarchar hv = new HiveVarchar(t, ((VarcharTypeInfo) typeInfo).getLength());
                row.set(c, hv);
                break;
            default:
                throw new SerDeException("Unsupported type " + typeInfo);
            }
        } catch (RuntimeException e) {
            row.set(c, null);
        }
    }
    return row;
}

From source file:edu.stanford.muse.util.EmailUtils.java

/** returns a histogram of the dates, bucketed in quantum of quantum, going backwards from endTime */
public static List<Integer> histogram(List<Date> dates, long endTime, long quantumMillis) {
    ArrayList<Integer> result = new ArrayList<Integer>();

    // input dates may not be sorted, but doesn't matter
    for (Date d : dates) {
        int slot = (int) ((endTime - d.getTime()) / quantumMillis);

        // ensure list has enough capacity because there may be gaps
        while (result.size() <= slot)
            result.add(0);//www  .  ja  v a 2 s  . c om

        // result.size() is at least slot+1    
        Integer I = result.get(slot);
        result.set(slot, I + 1);
    }

    return result;
}

From source file:org.processmining.analysis.performance.dottedchart.model.DottedChartModel.java

private void exch(ArrayList<String> key, int i, int j) {
    String swap = key.get(i);/*from  w  w w .  j a  va 2 s .  c  o m*/
    key.set(i, key.get(j));
    key.set(j, swap);
}

From source file:org.openmrs.module.accessmonitor.web.controller.AccessMonitorPersonController.java

@RequestMapping(value = "/module/accessmonitor/person", method = RequestMethod.GET)
public void person(ModelMap model, HttpServletRequest request) {

    offset = 0;/* ww w  .java2  s .c om*/
    // parse them to Date, null is acceptabl
    DateFormat format = new SimpleDateFormat("MM/dd/yyyy");
    // Get the from date and to date
    Date to = null;
    Date from = null;
    try {
        from = format.parse(request.getParameter("datepickerFrom"));
    } catch (Exception e) {
        //System.out.println("======From Date Empty=======");
    }
    try {
        to = format.parse(request.getParameter("datepickerTo"));
    } catch (Exception e) {
        //System.out.println("======To Date Empty=======");
    }

    // get all the records in the date range
    personAccessData = ((PersonAccessService) Context.getService(PersonAccessService.class))
            .getPersonAccessesByAccessDateOrderByPersonId(from, to);
    if (personAccessData == null) {
        personAccessData = new ArrayList<PersonServiceAccess>();
    }

    // get date for small graph
    Date toSmall = to;
    Date fromSmall = null;
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.DATE, 1);
    if (toSmall == null) {
        toSmall = calendar.getTime();
    } else {
        calendar.setTime(toSmall);
    }
    calendar.add(Calendar.DATE, -DAYNUM);
    fromSmall = calendar.getTime();

    List<String> dateStrings = new ArrayList<String>();
    for (int i = 0; i < DAYNUM; i++) {
        if (i == DAYNUM - 1) {
            dateStrings.add(format.format(toSmall));
        } else if (i == 0) {
            dateStrings.add(format.format(fromSmall));
        } else {
            dateStrings.add("");
        }
    }

    ArrayList<ArrayList<Integer>> tooltip = new ArrayList<ArrayList<Integer>>();
    tooltip.add(new ArrayList<Integer>());
    for (int j = 0; j < SHOWNUM + 1; j++) {
        tooltip.get(0).add(1000 + j);
    }
    for (int i = 1; i < DAYNUM + 1; i++) {
        tooltip.add(new ArrayList<Integer>());
        tooltip.get(i).add(i);
        for (int j = 0; j < SHOWNUM; j++) {
            tooltip.get(i).add(0);
        }
    }

    ArrayList<String> personIds = new ArrayList<String>();
    ArrayList<Integer> personCounts = new ArrayList<Integer>();
    for (PersonServiceAccess pa : personAccessData) {
        // data for big graph
        String idString = (pa.getPersonId() == null) ? "No ID" : pa.getPersonId().toString();
        int index = personIds.indexOf(idString);
        if (index < 0) {
            if (personIds.size() >= SHOWNUM)
                break;
            personIds.add(idString);
            personCounts.add(1);
            index = personIds.size() - 1;//index = personIds.indexOf(idString);
        } else {
            personCounts.set(index, personCounts.get(index) + 1);
        }
        // data for small graph
        if (pa.getAccessDate().after(fromSmall) && pa.getAccessDate().before(toSmall)) {
            int index2 = (int) ((pa.getAccessDate().getTime() - fromSmall.getTime()) / (1000 * 60 * 60 * 24));
            if (index2 < DAYNUM && index2 >= 0)
                tooltip.get(index2 + 1).set(index + 1, tooltip.get(index2 + 1).get(index + 1) + 1);
        }
    }
    String personIdString = JSONValue.toJSONString(personIds);
    String personCountString = JSONValue.toJSONString(personCounts);
    String dateSmallString = JSONValue.toJSONString(dateStrings);
    String tooltipdata = JSONValue.toJSONString(tooltip);
    model.addAttribute("personIds", personIdString);
    model.addAttribute("personCounts", personCountString);
    model.addAttribute("dateSmallString", dateSmallString);
    model.addAttribute("tooltipdata", tooltipdata);

    model.addAttribute("user", Context.getAuthenticatedUser());
    //model.addAttribute("tables1", personAccessData);
    //model.addAttribute("dateSmall", dateStrings);
    model.addAttribute("currentoffset", String.valueOf(offset));
}

From source file:com.predic8.membrane.core.transport.ssl.SSLContext.java

private void sortCiphers(ArrayList<String> ciphers) {
    ArrayList<CipherInfo> cipherInfos = new ArrayList<SSLContext.CipherInfo>(ciphers.size());

    for (String cipher : ciphers)
        cipherInfos.add(new CipherInfo(cipher));

    Collections.sort(cipherInfos, new Comparator<CipherInfo>() {
        @Override//from w  w  w . j  a v a 2 s .  co m
        public int compare(CipherInfo cipher1, CipherInfo cipher2) {
            return cipher2.points - cipher1.points;
        }
    });

    for (int i = 0; i < ciphers.size(); i++)
        ciphers.set(i, cipherInfos.get(i).cipher);
}

From source file:org.openmrs.module.accessmonitor.web.controller.AccessMonitorOrderController.java

@RequestMapping(value = "/module/accessmonitor/order", method = RequestMethod.GET)
public void person(ModelMap model, HttpServletRequest request) {

    offset = 0;/* www .j  ava 2s. c o  m*/
    // parse them to Date, null is acceptable
    DateFormat format = new SimpleDateFormat("MM/dd/yyyy");
    // Get the from date and to date
    Date to = null;
    Date from = null;
    try {
        from = format.parse(request.getParameter("datepickerFrom"));
    } catch (Exception e) {
        //System.out.println("======From Date Empty=======");
    }
    try {
        to = format.parse(request.getParameter("datepickerTo"));
    } catch (Exception e) {
        //System.out.println("======To Date Empty=======");
    }

    // get all the records in the date range
    orderAccessData = ((OrderAccessService) Context.getService(OrderAccessService.class))
            .getOrderAccessesByAccessDateOrderByPatientId(from, to);
    if (orderAccessData == null) {
        orderAccessData = new ArrayList<OrderServiceAccess>();
    }

    // get date for small graph
    Date toSmall = to;
    Date fromSmall = null;
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.DATE, 1);
    if (toSmall == null) {
        toSmall = calendar.getTime();
    } else {
        calendar.setTime(toSmall);
    }
    calendar.add(Calendar.DATE, -DAYNUM);
    fromSmall = calendar.getTime();

    List<String> dateStrings = new ArrayList<String>();
    for (int i = 0; i < DAYNUM; i++) {
        if (i == DAYNUM - 1) {
            dateStrings.add(format.format(toSmall));
        } else if (i == 0) {
            dateStrings.add(format.format(fromSmall));
        } else {
            dateStrings.add("");
        }
    }

    ArrayList<ArrayList<Integer>> tooltip = new ArrayList<ArrayList<Integer>>();
    tooltip.add(new ArrayList<Integer>());
    for (int j = 0; j < SHOWNUM + 1; j++) {
        tooltip.get(0).add(1000 + j);
    }
    for (int i = 1; i < DAYNUM + 1; i++) {
        tooltip.add(new ArrayList<Integer>());
        tooltip.get(i).add(i);
        for (int j = 0; j < SHOWNUM; j++) {
            tooltip.get(i).add(0);
        }
    }

    ArrayList<String> patientIds = new ArrayList<String>();
    ArrayList<Integer> patientCounts = new ArrayList<Integer>();
    for (OrderServiceAccess oa : orderAccessData) {
        // data for big graph
        String idString = (oa.getPatientId() == null) ? "No ID" : oa.getPatientId().toString();
        int index = patientIds.indexOf(idString);
        if (index < 0) {
            if (patientIds.size() >= SHOWNUM)
                break;
            patientIds.add(idString);
            patientCounts.add(1);
            index = patientIds.size() - 1;//index = personIds.indexOf(idString);
        } else {
            patientCounts.set(index, patientCounts.get(index) + 1);
        }
        // data for small graph
        if (oa.getAccessDate().after(fromSmall) && oa.getAccessDate().before(toSmall)) {
            int index2 = (int) ((oa.getAccessDate().getTime() - fromSmall.getTime()) / (1000 * 60 * 60 * 24));
            if (index2 < DAYNUM && index2 >= 0)
                tooltip.get(index2 + 1).set(index + 1, tooltip.get(index2 + 1).get(index + 1) + 1);
        }
    }
    String patientIdString = JSONValue.toJSONString(patientIds);
    String patientCountString = JSONValue.toJSONString(patientCounts);
    String dateSmallString = JSONValue.toJSONString(dateStrings);
    String tooltipdata = JSONValue.toJSONString(tooltip);
    model.addAttribute("patientIds", patientIdString);
    model.addAttribute("patientCounts", patientCountString);
    model.addAttribute("dateSmallString", dateSmallString);
    model.addAttribute("tooltipdata", tooltipdata);

    model.addAttribute("user", Context.getAuthenticatedUser());
    //model.addAttribute("tables1", orderAccessData);
    //model.addAttribute("dateSmall", dateStrings);
    model.addAttribute("currentoffset", String.valueOf(offset));
}