Example usage for java.util ListIterator set

List of usage examples for java.util ListIterator set

Introduction

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

Prototype

void set(E e);

Source Link

Document

Replaces the last element returned by #next or #previous with the specified element (optional operation).

Usage

From source file:org.deegree.services.wms.WMSSimilarityIntegrationTest.java

@Test
public void testSimilarity() throws IOException {
    String base = "http://localhost:" + System.getProperty("portnumber");
    base += "/deegree-wms-similarity-tests/services" + request;
    InputStream in = retrieve(STREAM, base);

    byte[] bs = null;

    ListIterator<byte[]> iter = response.listIterator();
    while (iter.hasNext()) {
        byte[] resp = iter.next();
        try {/*from  w  w  w .j  ava 2  s  . c  om*/
            BufferedImage img2 = ImageIO.read(new ByteArrayInputStream(resp));
            bs = IOUtils.toByteArray(in);
            BufferedImage img1 = ImageIO.read(new ByteArrayInputStream(bs));
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ImageIO.write(img1, "tif", bos);
            bos.close();
            in = new ByteArrayInputStream(bs = bos.toByteArray());
            bos = new ByteArrayOutputStream();
            bos.close();
            ImageIO.write(img2, "tif", bos);
            iter.set(bos.toByteArray());
        } catch (Throwable t) {
            t.printStackTrace();
            // just compare initial byte arrays
        }
    }

    double sim = 0;
    for (byte[] response : this.response) {
        in = new ByteArrayInputStream(bs);
        if (MathUtils.isZero(sim) || Math.abs(1.0 - sim) > 0.01 || Double.isNaN(sim)) {
            sim = Math.max(sim, determineSimilarity(in, new ByteArrayInputStream(response)));
        }
    }

    if (Math.abs(1.0 - sim) > 0.01) {
        System.out.println(
                "Trying to store request/response in tempdir: expected/response" + ++numFailed + ".tif");
        try {
            int idx = 0;
            for (byte[] response : this.response) {
                IOUtils.write(response, new FileOutputStream(
                        System.getProperty("java.io.tmpdir") + "/expected" + ++idx + "_" + numFailed + ".tif"));
            }
            IOUtils.write(bs, new FileOutputStream(
                    System.getProperty("java.io.tmpdir") + "/response" + numFailed + ".tif"));
        } catch (Throwable t) {
        }
    }
    Assert.assertEquals("Images are not similar enough for " + name + ". Request: " + request, 1.0, sim, 0.01);
}

From source file:com.netflix.config.ConcurrentCompositeConfiguration.java

/**
 * Get a List of objects associated with the given configuration key.
 * If the key doesn't map to an existing object, the default value
 * is returned.//from   www.j  a  va 2s .c om
 *
 * @param key The configuration key.
 * @param defaultValue The default value.
 * @return The associated List of value.
 * 
 */
@Override
public List getList(String key, List defaultValue) {
    List<Object> list = new ArrayList<Object>();

    // add all elements from the first configuration containing the requested key
    Iterator<AbstractConfiguration> it = configList.iterator();
    if (overrideProperties.containsKey(key)) {
        appendListProperty(list, overrideProperties, key);
    }
    while (it.hasNext() && list.isEmpty()) {
        Configuration config = it.next();
        if ((config != containerConfiguration || containerConfigurationChanged) && config.containsKey(key)) {
            appendListProperty(list, config, key);
        }
    }

    // add all elements from the in memory configuration
    if (list.isEmpty()) {
        appendListProperty(list, containerConfiguration, key);
    }

    if (list.isEmpty()) {
        return defaultValue;
    }

    ListIterator<Object> lit = list.listIterator();
    while (lit.hasNext()) {
        lit.set(interpolate(lit.next()));
    }

    return list;
}

From source file:org.tinymediamanager.core.movie.MovieSettings.java

public List<String> getBadWords() {
    // convert to lowercase for easy contains checking
    ListIterator<String> iterator = badWords.listIterator();
    while (iterator.hasNext()) {
        iterator.set(iterator.next().toLowerCase(Locale.ROOT));
    }//  w ww . j a  va  2s  . co  m
    return badWords;
}

From source file:com.kunze.androidlocaltodo.TaskListActivity.java

private void LoadAstrid() {
    // Look for a zip file in the proper location
    String loc = Environment.getExternalStorageDirectory() + "/AstridImport/";
    AlertDialog.Builder errorBuilder = new AlertDialog.Builder(this);
    errorBuilder.setTitle("Error reading Astrid Import!");
    ZipInputStream zipStream = null;
    InputStream stream = null;// w  ww.  j  a v  a  2s.  c  o  m
    try {
        // Try to safely open the file
        String errText = "Cannot find Astrid file in " + loc;
        File astridDir = new File(loc);
        if (!astridDir.isDirectory()) {
            throw new Exception(errText);
        }

        File[] files = astridDir.listFiles();
        if (files.length != 1) {
            throw new Exception(errText);
        }

        File astridFile = files[0];
        if (!astridFile.isFile()) {
            throw new Exception(errText);
        }

        // Try to unzip the file and unpack the tasks
        errText = "Could not unzip file " + astridFile.getAbsolutePath();
        stream = new FileInputStream(astridFile);
        zipStream = new ZipInputStream(stream);

        ZipEntry tasksEntry = null;
        while ((tasksEntry = zipStream.getNextEntry()) != null) {
            if (tasksEntry.getName().equals("tasks.csv")) {
                break;
            }
        }
        if (tasksEntry == null) {
            throw new Exception(errText);
        }

        int size = (int) tasksEntry.getSize();
        byte tasksContent[] = new byte[size];
        int offset = 0;
        while (size != 0) {
            int read = zipStream.read(tasksContent, offset, size);
            if (read == 0) {
                throw new Exception(errText);
            }
            offset += read;
            size -= read;
        }

        String tasksString = new String(tasksContent, "UTF-8");

        // Parse the tasks in the task list
        errText = "Could not parse task list";
        List<String> taskLines = new LinkedList<String>(Arrays.asList(tasksString.split("\n")));
        // Remove the header row
        taskLines.remove(0);
        // Some tasks have newlines in quotes, so we have to adjust for that.
        ListIterator<String> it = taskLines.listIterator();
        while (it.hasNext()) {
            String task = it.next();
            while (CountQuotes(task) % 2 == 1) {
                it.remove();
                task += it.next();
            }
            it.set(task);
        }
        for (String taskLine : taskLines) {
            List<String> taskFields = new LinkedList<String>(Arrays.asList(taskLine.split(",", -1)));
            // Some tasks have commas in quotes, so we have to adjust for that.
            it = taskFields.listIterator();
            while (it.hasNext()) {
                String field = it.next();
                while (CountQuotes(field) % 2 == 1) {
                    it.remove();
                    field += it.next();
                }
                it.set(field);
            }

            Task taskElement = new Task();
            taskElement.mName = taskFields.get(0);
            taskElement.mDescription = taskFields.get(8);

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);

            taskElement.mDueDate = Calendar.getInstance();
            taskElement.mDueDate.setTime(dateFormat.parse(taskFields.get(4)));
            String completedString = taskFields.get(9);
            taskElement.mCompletedDate = Calendar.getInstance();
            if (completedString.equals("")) {
                taskElement.mCompletedDate.setTimeInMillis(0);
            } else {
                taskElement.mCompletedDate.setTime(dateFormat.parse(completedString));
            }
            taskElement.mRepeatUnit = Task.RepeatUnit.NONE;
            taskElement.mRepeatTime = 0;
            taskElement.mRepeatFromComplete = false;
            String repeatString = taskFields.get(6);
            String repeatFields[] = repeatString.split(":");
            if (repeatFields[0].equals("RRULE")) {
                repeatFields = repeatFields[1].split(";");
                String freqFields[] = repeatFields[0].split("=");
                if (freqFields[0].equals("FREQ")) {
                    if (freqFields[1].equals("YEARLY")) {
                        taskElement.mRepeatUnit = Task.RepeatUnit.YEARS;
                    } else if (freqFields[1].equals("MONTHLY")) {
                        taskElement.mRepeatUnit = Task.RepeatUnit.MONTHS;
                    } else if (freqFields[1].equals("WEEKLY")) {
                        taskElement.mRepeatUnit = Task.RepeatUnit.WEEKS;
                    } else if (freqFields[1].equals("DAILY")) {
                        taskElement.mRepeatUnit = Task.RepeatUnit.DAYS;
                    }
                }
                freqFields = repeatFields[1].split("=");
                if (freqFields[0].equals("INTERVAL")) {
                    taskElement.mRepeatTime = Integer.valueOf(freqFields[1]);
                }
                if (repeatFields.length > 2 && repeatFields[2] != null) {
                    freqFields = repeatFields[2].split("=");
                    if (freqFields[0].equals("FROM") && freqFields[1].equals("COMPLETION")) {
                        taskElement.mRepeatFromComplete = true;
                    }
                }
            }
            mDB.AddTask(taskElement);
        }

        RefreshView();
    } catch (Exception e) {
        AlertDialog dlg = errorBuilder.setMessage(e.getMessage()).create();
        dlg.show();
    } finally {

        try {
            if (zipStream != null) {
                zipStream.close();
            }
            if (stream != null) {
                stream.close();
            }
        } catch (Exception e) {
            AlertDialog dlg = errorBuilder.setMessage(e.getMessage()).create();
            dlg.show();
        }
    }
}

From source file:com.vizury.videocache.product.ProductDetail.java

private ProductDetail[] getProductDataFromList(CacheConnect cache, String productList,
        HashMap<String, ProductDetail> recommendedProductDetail, int numberOfRecommendedProducts) {
    String[] productIdArray = productList.replace("\"", "").split(",");
    List<ProductDetail> productDetailList = new ArrayList<>();
    List<ProductDetail> requestProductDetailList = new ArrayList<>();
    for (String pid : productIdArray) {
        if (!pid.equals(productId)) {
            if (!recommendedProductDetail.containsKey(namespace + "_1_" + pid)) {
                requestProductDetailList.add(new ProductDetail(pid, namespace));
            }//w  ww.  j  av  a  2 s .c om
            productDetailList.add(new ProductDetail(pid, namespace));
        }
    }
    Map<String, Object> productDetailMap = cache.getBulk(requestProductDetailList, "_1_");
    if (productDetailMap != null) {
        ListIterator iterator = productDetailList.listIterator();
        while (iterator.hasNext()) {
            ProductDetail productDetail = (ProductDetail) iterator.next();
            if (productDetailMap.containsKey(namespace + "_1_" + productDetail.getProductId())) {
                productDetail.jsonToProductDetail(
                        (String) productDetailMap.get(namespace + "_1_" + productDetail.getProductId()));
                recommendedProductDetail.put(namespace + "_1_" + productDetail.getProductId(), productDetail);
            } else {
                iterator.set(recommendedProductDetail.get(namespace + "_1_" + productDetail.getProductId()));
            }
        }
    } else {
        return null;
    }
    if (productDetailList.size() <= numberOfRecommendedProducts) {
        return productDetailList.toArray(new ProductDetail[productDetailList.size()]);
    } else {
        Random rand = new Random();
        int randomIndex;
        int index;
        ProductDetail[] productDetail = new ProductDetail[numberOfRecommendedProducts];
        for (index = 0; index < numberOfRecommendedProducts; index++) {
            randomIndex = rand.nextInt(productDetailList.size());
            productDetail[index] = productDetailList.get(randomIndex);
            productDetailList.remove(randomIndex);
        }
        return productDetail;
    }
}

From source file:org.apache.hadoop.registry.client.impl.zk.RegistrySecurity.java

/**
 * Split up a list of the form/*from   www . java 2s . c  o m*/
 * <code>sasl:mapred@,digest:5f55d66, sasl@yarn@EXAMPLE.COM</code>
 * into a list of possible ACL values, trimming as needed
 *
 * The supplied realm is added to entries where
 * <ol>
 *   <li>the string begins "sasl:"</li>
 *   <li>the string ends with "@"</li>
 * </ol>
 * No attempt is made to validate any of the acl patterns.
 *
 * @param aclString list of 0 or more ACLs
 * @param realm realm to add
 * @return a list of split and potentially patched ACL pairs.
 *
 */
public List<String> splitAclPairs(String aclString, String realm) {
    List<String> list = Lists.newArrayList(Splitter.on(',').omitEmptyStrings().trimResults().split(aclString));
    ListIterator<String> listIterator = list.listIterator();
    while (listIterator.hasNext()) {
        String next = listIterator.next();
        if (next.startsWith(SCHEME_SASL + ":") && next.endsWith("@")) {
            listIterator.set(next + realm);
        }
    }
    return list;
}

From source file:org.kuali.rice.krms.impl.repository.RuleBoServiceImpl.java

/**
 * Transfer any ActionAttributeBos that still apply from the existing actions, while updating their values.
 *
 * <p>This method is side effecting, it replaces elements in the passed in toUpdateActionBos collection. </p>
 *
 * @param toUpdateActionBos the new ActionBos which will (later) be persisted
 * @param existingActionBos the ActionBos which have been fetched from the database
 *//*w  ww .j a  v a 2 s  . c o m*/
private void reconcileActionAttributes(List<ActionBo> toUpdateActionBos, List<ActionBo> existingActionBos) {
    for (ActionBo toUpdateAction : toUpdateActionBos) {

        ActionBo matchingExistingAction = findMatchingExistingAction(toUpdateAction, existingActionBos);

        if (matchingExistingAction == null) {
            continue;
        }

        ListIterator<ActionAttributeBo> toUpdateAttributesIter = toUpdateAction.getAttributeBos()
                .listIterator();

        while (toUpdateAttributesIter.hasNext()) {
            ActionAttributeBo toUpdateAttribute = toUpdateAttributesIter.next();

            ActionAttributeBo matchingExistingAttribute = findMatchingExistingAttribute(toUpdateAttribute,
                    matchingExistingAction.getAttributeBos());

            if (matchingExistingAttribute == null) {
                continue;
            }

            // set the new value into the existing attribute, then replace the new attribute with the existing one
            matchingExistingAttribute.setValue(toUpdateAttribute.getValue());
            toUpdateAttributesIter.set(matchingExistingAttribute);
        }
    }
}

From source file:es.uvigo.ei.sing.adops.operations.running.ExecuteExperimentBySteps.java

private void replaceSequenceNamesAln(File inputFile, File outputFile) throws IOException {
    final Map<String, String> names = this.experiment.getNames();
    final List<String> lines = FileUtils.readLines(inputFile);

    int maxLength = Integer.MIN_VALUE;
    for (Map.Entry<String, String> name : names.entrySet()) {
        maxLength = Math.max(maxLength, name.getValue().length());
    }/*  ww  w  .  j a  va 2s  .c  om*/

    for (Map.Entry<String, String> name : names.entrySet()) {
        String newName = name.getValue();

        while (newName.length() < maxLength) {
            newName += ' ';
        }

        name.setValue(newName);
    }

    final ListIterator<String> itLines = lines.listIterator();
    if (itLines.hasNext())
        itLines.next();

    // TODO Review parsing
    while (itLines.hasNext()) {
        itLines.next(); // White line

        String line = null;
        // Sequences
        while (itLines.hasNext()) {
            line = itLines.next();
            if (line.isEmpty())
                break;
            final String[] lineSplit = line.split("\\s+");
            final String name = lineSplit.length == 0 ? "" : lineSplit[0];

            if (names.get(name) == null)
                break;

            itLines.set(names.get(name) + "   " + lineSplit[1]);
        }

        // Marks line
        if (line != null && !line.isEmpty() && line.startsWith(" ")) {
            String newLine = line;

            if (maxLength < 13)
                newLine = newLine.substring(13 - maxLength);
            else
                for (int i = 16; i < maxLength + 3; i++) {
                    newLine = ' ' + newLine;
                }

            itLines.set(newLine);
        }
    }

    FileUtils.writeLines(outputFile, lines);
}

From source file:org.apache.usergrid.persistence.Results.java

public void replace(Entity entity) {
    entitiesMap = null;/*from   w  w  w. j  av a2 s.  c  om*/
    if ((this.entity != null) && (this.entity.getUuid().equals(entity.getUuid()))) {
        this.entity = entity;
    }
    if (entities != null) {
        ListIterator<Entity> i = entities.listIterator();
        while (i.hasNext()) {
            Entity e = i.next();
            if (e.getUuid().equals(entity.getUuid())) {
                i.set(entity);
            }
        }
    }
}

From source file:org.exfio.weave.account.exfiopeer.ExfioPeerV1.java

public Message[] getPendingClientAuthMessages() throws WeaveException {

    List<Message> msgPending = new ArrayList<Message>(
            Arrays.asList(comms.getPendingMessages(MESSAGE_TYPE_CLIENTAUTHREQUEST)));

    ListIterator<Message> iterPending = msgPending.listIterator();
    while (iterPending.hasNext()) {
        Message msg = iterPending.next();

        Client otherClient = comms.getClient(msg.getSourceClientId());

        //Nothing to do if status no longer pending
        if (!otherClient.getStatus().equals("pending")) {
            Log.getInstance().info(String.format("Client '%s' (%s) status '%s'. Discarding client auth request",
                    otherClient.getClientName(), otherClient.getClientId(), otherClient.getStatus()));
            comms.updateMessageSession(msg.getMessageSessionId(), "closed");
            //remove message from pending list
            iterPending.remove();//  www. j a v a2 s.  co  m
            continue;
        }

        //Re instansiate as ClientAuthRequestMessage
        iterPending.set(new ClientAuthRequestMessage(msg));
    }
    return msgPending.toArray(new Message[0]);
}