Example usage for java.util ListIterator hasNext

List of usage examples for java.util ListIterator hasNext

Introduction

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

Prototype

boolean hasNext();

Source Link

Document

Returns true if this list iterator has more elements when traversing the list in the forward direction.

Usage

From source file:com.tacitknowledge.util.migration.jdbc.SqlScriptMigrationTask.java

/**
 * Executes the passed sql in the passed context.
 *
 * @param ctx       the <code>MigrationContext> to execute the SQL in
 * @param sqlToExec the SQL to execute//  w w w . ja v  a2s  .  co m
 * @throws MigrationException thrown if there is an error when executing the SQL
 */
private void executeSql(MigrationContext ctx, String sqlToExec) throws MigrationException {
    JdbcMigrationContext context = (JdbcMigrationContext) ctx;

    Connection conn = null;
    Statement stmt = null;
    String sqlStatement = "";
    ListIterator listIterator = null;
    try {
        conn = context.getConnection();

        // cleaning the slate before we execute the patch.
        // This was inspired by a Sybase ASE server that did not allow
        // ALTER TABLE statements in multi-statement transactions.  Instead of putting
        // a if(sybase) conditional, we decided to clean the slate for everyone.
        context.commit();

        List sqlStatements = getSqlStatements(context, sqlToExec);
        for (listIterator = sqlStatements.listIterator(); listIterator.hasNext();) {
            sqlStatement = (String) listIterator.next();
            log.debug(getName() + ": Attempting to execute: " + sqlStatement);

            stmt = conn.createStatement();

            // handle sybase special case with illegal commands in multi
            // command transactions
            if (isSybase(context) && SybaseUtil.containsIllegalMultiStatementTransactionCommand(sqlStatement)) {
                log.warn("Committing current transaction since patch " + getName()
                        + " contains commands that are not allowed in multi statement"
                        + " transactions.  If the patch contains errors, this patch may"
                        + " not be rolled back cleanly.");
                context.commit();
                stmt.execute(sqlStatement);
                context.commit();
            } else // regular case
            {
                stmt.execute(sqlStatement);
            }

            SqlUtil.close(null, stmt, null);
        }

        context.commit();
    } catch (Exception e) {
        String message = getName() + ": Error running SQL at statement number " + listIterator.previousIndex()
                + " \"" + sqlStatement + "\"";
        log.error(message, e);

        if (e instanceof SQLException) {
            if (((SQLException) e).getNextException() != null) {
                log.error("Chained SQL Exception", ((SQLException) e).getNextException());
            }
        }

        context.rollback();
        throw new MigrationException(message, e);
    } finally {
        SqlUtil.close(null, stmt, null);
    }
}

From source file:org.slc.sli.dashboard.unit.client.SDKAPIClientTest.java

@Test
public void testGetSchools()
        throws URISyntaxException, IOException, MessageProcessingException, SLIClientException {
    SDKAPIClient client = new SDKAPIClient() {
        @Override/*w w  w .  j  a v  a  2  s. c  o m*/
        public String getId(String token) {
            return null;
        }

        @Override
        public List<GenericEntity> getSectionsForTeacher(String teacherId, String token,
                Map<String, String> params) {
            return null;
        }

        @Override
        public List<GenericEntity> getSectionsForNonEducator(String token, Map<String, String> params) {
            return null;
        }
    };
    SLIClientFactory factory = mock(SLIClientFactory.class);
    when(factory.getClientWithSessionToken(anyString())).thenReturn(mockSdk);
    client.setClientFactory(factory);

    SecurityContextHolder.getContext().setAuthentication(new Authentication() {
        @Override
        public String getName() {
            return null;
        }

        @Override
        public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
        }

        @Override
        public boolean isAuthenticated() {
            return false;
        }

        @Override
        public Object getPrincipal() {
            return null;
        }

        @Override
        public Object getDetails() {
            return null;
        }

        @Override
        public Object getCredentials() {
            return null;
        }

        @Override
        public Collection<GrantedAuthority> getAuthorities() {
            return Collections.emptyList();
        }
    });

    String token = "token";
    String key = "schoolId";
    String[] idArr = { "Illinois PS145", "Illinois PS200" };
    List<String> schoolIds = Arrays.asList(idArr);

    String filename = getFilename(MOCK_DATA_DIRECTORY + "common/" + MOCK_SCHOOL_FILE);
    when(mockSdk.read(anyString())).thenReturn(fromFileWithIDList(filename, schoolIds, key));

    List<GenericEntity> schoolList = client.getSchools(token, schoolIds);

    assertNotNull(schoolList);
    assertEquals(2, schoolList.size());
    ListIterator<GenericEntity> li = schoolList.listIterator();
    while (li.hasNext()) {
        assertTrue(schoolIds.contains(li.next().getString(key)));
    }
}

From source file:de.unisb.cs.st.javaslicer.tracer.instrumentation.PauseTracingInstrumenter.java

@SuppressWarnings("unchecked")
public void transformMethod(final MethodNode method, final ListIterator<MethodNode> methodIt,
        final String className) {
    if ((method.access & ACC_ABSTRACT) != 0 || (method.access & ACC_NATIVE) != 0)
        return;/* w w  w .  j  av  a  2  s .c  om*/

    int tracerLocalVarIndex = (method.access & Opcodes.ACC_STATIC) == 0 ? 1 : 0;
    for (final Type t : Type.getArgumentTypes(method.desc))
        tracerLocalVarIndex += t.getSize();

    // increment number of local variables by one (for the threadtracer)
    ++method.maxLocals;

    // and increment all local variable indexes after the new one by one
    for (final Object o : method.localVariables) {
        final LocalVariableNode localVar = (LocalVariableNode) o;
        if (localVar.index >= tracerLocalVarIndex)
            ++localVar.index;
    }
    final LabelNode l0 = new LabelNode();
    final LabelNode l1 = new LabelNode();

    final ListIterator<AbstractInsnNode> insnIt = method.instructions.iterator();

    insnIt.add(new MethodInsnNode(INVOKESTATIC, Type.getInternalName(Tracer.class), "getInstance",
            "()L" + Type.getInternalName(Tracer.class) + ";"));
    insnIt.add(new MethodInsnNode(INVOKEVIRTUAL, Type.getInternalName(Tracer.class), "getThreadTracer",
            "()L" + Type.getInternalName(ThreadTracer.class) + ";"));
    insnIt.add(new InsnNode(DUP));
    insnIt.add(new VarInsnNode(ASTORE, tracerLocalVarIndex));
    insnIt.add(new MethodInsnNode(INVOKEINTERFACE, Type.getInternalName(ThreadTracer.class), "pauseTracing",
            "()V"));
    insnIt.add(l0);

    while (insnIt.hasNext()) {
        final AbstractInsnNode insn = insnIt.next();
        switch (insn.getType()) {
        case AbstractInsnNode.INSN:
            switch (insn.getOpcode()) {
            case IRETURN:
            case LRETURN:
            case FRETURN:
            case DRETURN:
            case ARETURN:
            case RETURN:
                insnIt.previous();
                insnIt.add(new VarInsnNode(ALOAD, tracerLocalVarIndex));
                insnIt.add(new MethodInsnNode(INVOKEINTERFACE, Type.getInternalName(ThreadTracer.class),
                        "resumeTracing", "()V"));
                insnIt.next();
            }
            break;
        case AbstractInsnNode.IINC_INSN:
            if (((IincInsnNode) insn).var >= tracerLocalVarIndex)
                ++((IincInsnNode) insn).var;
            break;
        case AbstractInsnNode.VAR_INSN:
            if (((VarInsnNode) insn).var >= tracerLocalVarIndex)
                ++((VarInsnNode) insn).var;
            break;
        default:
            break;
        }
    }

    method.instructions.add(l1);

    method.instructions.add(new VarInsnNode(ALOAD, tracerLocalVarIndex));
    method.instructions.add(new MethodInsnNode(INVOKEINTERFACE, Type.getInternalName(ThreadTracer.class),
            "resumeTracing", "()V"));
    method.instructions.add(new InsnNode(ATHROW));

    method.tryCatchBlocks.add(new TryCatchBlockNode(l0, l1, l1, null));

    // finally: create a copy of the method that gets the ThreadTracer as argument
    if (!"<clinit>".equals(method.name) && this.tracer.wasRedefined(className)) {
        final Type[] oldMethodArguments = Type.getArgumentTypes(method.desc);
        final Type[] newMethodArguments = Arrays.copyOf(oldMethodArguments, oldMethodArguments.length + 1);
        newMethodArguments[oldMethodArguments.length] = Type.getType(ThreadTracer.class);
        final String newMethodDesc = Type.getMethodDescriptor(Type.getReturnType(method.desc),
                newMethodArguments);
        final MethodNode newMethod = new MethodNode(method.access, method.name, newMethodDesc, method.signature,
                (String[]) method.exceptions.toArray(new String[method.exceptions.size()]));
        methodIt.add(newMethod);

        final Map<LabelNode, LabelNode> newMethodLabels = LazyMap.decorate(new HashMap<LabelNode, LabelNode>(),
                new Factory() {
                    @Override
                    public Object create() {
                        return new LabelNode();
                    }
                });

        // copy the local variables information to the new method
        for (final Object o : method.localVariables) {
            final LocalVariableNode lv = (LocalVariableNode) o;
            newMethod.localVariables.add(new LocalVariableNode(lv.name, lv.desc, lv.signature,
                    newMethodLabels.get(lv.start), newMethodLabels.get(lv.end), lv.index));
        }

        newMethod.maxLocals = method.maxLocals;
        newMethod.maxStack = method.maxStack;

        // copy the try-catch-blocks
        for (final Object o : method.tryCatchBlocks) {
            final TryCatchBlockNode tcb = (TryCatchBlockNode) o;
            newMethod.tryCatchBlocks.add(new TryCatchBlockNode(newMethodLabels.get(tcb.start),
                    newMethodLabels.get(tcb.end), newMethodLabels.get(tcb.handler), tcb.type));
        }

        // skip the first 4 instructions, replace them with this:
        newMethod.instructions.add(new VarInsnNode(ALOAD, tracerLocalVarIndex));
        final Iterator<AbstractInsnNode> oldInsnIt = method.instructions.iterator(4);
        // and add all the other instructions
        while (oldInsnIt.hasNext()) {
            final AbstractInsnNode insn = oldInsnIt.next();
            newMethod.instructions.add(insn.clone(newMethodLabels));
        }
    }
}

From source file:geogebra.common.kernel.implicit.AlgoIntersectImplicitpolys.java

private void insert(double[] pair) {
    ListIterator<double[]> it = valPairs.listIterator();
    double eps = 1E-3; //find good value...
    while (it.hasNext()) {
        double[] p = it.next();
        if (Kernel.isGreater(p[0], pair[0], eps)) {
            it.previous();/*www. j  a  v a2  s  . co m*/
            break;
        }
        if (Kernel.isEqual(p[0], pair[0], eps)) {
            if (Kernel.isGreater(p[1], pair[1], eps)) {
                it.previous();
                break;
            }
            if (Kernel.isEqual(p[1], pair[1], eps))
                return; //do not add
        }
    }
    it.add(pair);
}

From source file:com.projity.pm.graphic.spreadsheet.common.CommonSpreadSheet.java

/**
 * Used by find dialog//from  w  w w  . j a v a2s  .  c om
 */
public boolean findNext(SearchContext context) {
    SpreadSheetSearchContext ctx = (SpreadSheetSearchContext) context;

    int row = this.getCurrentRow();
    // make sure in bounds
    if (row < 0)
        row = 0;
    if (row >= getCache().getSize())
        row = getCache().getSize() - 1;

    ListIterator i = getCache().getIterator(row);
    if (ctx.getRow() != -1) { // after the first search, need to move ahead or back
        if (ctx.isForward())
            if (i.hasNext())
                i.next();
            else if (i.hasPrevious())
                i.previous();
    }

    boolean found = false;
    GraphicNode gnode = null;
    Object obj;
    Node node;
    while (ctx.isForward() ? i.hasNext() : i.hasPrevious()) {
        gnode = (GraphicNode) (ctx.isForward() ? i.next() : i.previous());
        if (gnode.isVoid())
            continue;
        node = gnode.getNode();
        obj = node.getImpl();
        if (ctx.matches(obj)) {
            found = true;
            break;
        }
    }
    if (found) {
        int r = getCache().getRowAt(gnode);
        int col = getFieldArray().indexOf(ctx.getField()) - 1;
        this.changeSelection(r, col, false, false);
        ctx.setRow(r);
    }
    return found;
}

From source file:vteaexploration.plottools.panels.XYExplorationPanel.java

@Override
public int getSelectedObjects() {
    Gate gate;/* w  w  w . ja  v a2s. com*/
    ListIterator<Gate> gate_itr = gates.listIterator();

    //.get
    int selected = 0;
    int gated = 0;
    int total = 0;

    ArrayList<MicroObject> result = new ArrayList<MicroObject>();

    while (gate_itr.hasNext()) {
        gate = gate_itr.next();
        if (gate.getSelected()) {
            Path2D path = gate.createPath2DInChartSpace();

            ArrayList<MicroObject> volumes = (ArrayList) this.plotvalues.get(1);
            MicroObjectModel volume;

            double xValue = 0;
            double yValue = 0;

            ListIterator<MicroObject> it = volumes.listIterator();
            try {
                while (it.hasNext()) {
                    volume = it.next();
                    if (volume != null) {
                        xValue = ((Number) processPosition(currentX, (MicroObject) volume)).doubleValue();
                        yValue = ((Number) processPosition(currentY, (MicroObject) volume)).doubleValue();
                        if (path.contains(xValue, yValue)) {
                            result.add((MicroObject) volume);
                        }
                    }
                }
            } catch (NullPointerException e) {
                return 0;
            }
        }
    }

    //System.out.println("RESULT: total gates " + gates.size() + ": " + this.getTitle() + ", Gated: " + selected + ", Total: " + total + ", for: " + 100 * (new Double(selected).doubleValue() / (new Double(total)).doubleValue()) + "%");
    return result.size();
}

From source file:com.xmobileapp.rockplayer.LastFmEventImporter.java

/**********************************************
 * // w  w  w.  ja v a  2 s .  c  om
 * insertListInListByDate
 * @param singleArtistEventList
 * 
 **********************************************/
public void insertListInListByDate(LinkedList<ArtistEvent> singleArtistEventList) {
    /*
     * If this artist List is empty just return
     */
    if (singleArtistEventList.isEmpty())
        return;

    /*
     * If the big list is empty just add this one to it
     */
    if (artistEventList.isEmpty()) {
        artistEventList.addAll(singleArtistEventList);
        return;
    }

    /*
     * Insert the items (normal case)
     */
    ListIterator<ArtistEvent> artistEventListIterator = artistEventList.listIterator(0);
    ListIterator<ArtistEvent> singleArtistEventListIterator = singleArtistEventList.listIterator(0);
    ArtistEvent artistEvent;
    ArtistEvent singleArtistEvent;
    while (singleArtistEventListIterator.hasNext()) {
        /*
         * Not yet at the end of the big list
         */
        if (artistEventListIterator.hasNext()) {
            singleArtistEvent = singleArtistEventListIterator.next();
            artistEvent = artistEventListIterator.next();
            while (singleArtistEvent.dateInMillis > artistEvent.dateInMillis) {
                if (artistEventListIterator.hasNext())
                    artistEvent = artistEventListIterator.next();
                else {
                    if (artistEventListIterator.previousIndex() >= MAX_EVENT_LIST_SIZE) {
                        return;
                    } else {
                        break; // TODO: add missing items to the big list
                    }
                }
            }
            artistEventListIterator.previous();
            artistEventListIterator.add(singleArtistEvent);
        }
        /*
         * At the end of the big list (but not of the 'small' list
         */
        else {
            if (artistEventListIterator.previousIndex() >= MAX_EVENT_LIST_SIZE)
                return;
            singleArtistEvent = singleArtistEventListIterator.next();
            artistEventListIterator.add(singleArtistEvent);
            artistEventListIterator.next();
        }
    }

    /*
     * Keep the list size in check
     */
    while (artistEventList.size() > MAX_EVENT_LIST_SIZE)
        artistEventList.removeLast();
}

From source file:playground.christoph.evacuation.analysis.EvacuationTimePictureWriter.java

public FolderType getLinkFolder(String transportMode, Map<Id, BasicLocation> locations,
        Map<Id, Double> evacuationTimes) throws IOException {

    calcMaxEvacuationTime(evacuationTimes);

    /*//from www.  j  a  v  a 2  s.c om
     * create Folders and connect them
     */
    FolderType mainFolder = this.kmlObjectFactory.createFolderType();
    FolderType linkFolder = this.kmlObjectFactory.createFolderType();
    FolderType facilityFolder = this.kmlObjectFactory.createFolderType();
    FolderType linkFolderA = this.kmlObjectFactory.createFolderType(); // 0 .. 10 valid Trips
    FolderType linkFolderB = this.kmlObjectFactory.createFolderType(); // 10 .. 100 valid Trips
    FolderType linkFolderC = this.kmlObjectFactory.createFolderType(); // 100 .. 1000 valid Trips
    FolderType linkFolderD = this.kmlObjectFactory.createFolderType(); // 1000 and more valid Trips
    FolderType facilityFolderA = this.kmlObjectFactory.createFolderType(); // 0 .. 10 valid Trips
    FolderType facilityFolderB = this.kmlObjectFactory.createFolderType(); // 10 .. 100 valid Trips
    FolderType facilityFolderC = this.kmlObjectFactory.createFolderType(); // 100 .. 1000 valid Trips
    FolderType facilityFolderD = this.kmlObjectFactory.createFolderType(); // 1000 and more valid Trips

    mainFolder.setName("Evacuation Times " + transportMode);
    linkFolder.setName("Links");
    facilityFolder.setName("Facilities");
    linkFolderA.setName("Links with 0..9 valid Trips");
    linkFolderB.setName("Links with 10..99 valid Trips");
    linkFolderC.setName("Links with 100..9 valid Trips");
    linkFolderD.setName("Links with 1000 and more valid Trips");
    facilityFolderA.setName("Facilities with 0..9 valid Trips");
    facilityFolderB.setName("Facilities with 10..99 valid Trips");
    facilityFolderC.setName("Facilities with 100..9 valid Trips");
    facilityFolderD.setName("Facilities with 1000 and more valid Trips");

    mainFolder.getAbstractFeatureGroup().add(this.kmlObjectFactory.createFolder(linkFolder));
    mainFolder.getAbstractFeatureGroup().add(this.kmlObjectFactory.createFolder(facilityFolder));
    linkFolder.getAbstractFeatureGroup().add(this.kmlObjectFactory.createFolder(linkFolderA));
    linkFolder.getAbstractFeatureGroup().add(this.kmlObjectFactory.createFolder(linkFolderB));
    linkFolder.getAbstractFeatureGroup().add(this.kmlObjectFactory.createFolder(linkFolderC));
    linkFolder.getAbstractFeatureGroup().add(this.kmlObjectFactory.createFolder(linkFolderD));
    facilityFolder.getAbstractFeatureGroup().add(this.kmlObjectFactory.createFolder(facilityFolderA));
    facilityFolder.getAbstractFeatureGroup().add(this.kmlObjectFactory.createFolder(facilityFolderB));
    facilityFolder.getAbstractFeatureGroup().add(this.kmlObjectFactory.createFolder(facilityFolderC));
    facilityFolder.getAbstractFeatureGroup().add(this.kmlObjectFactory.createFolder(facilityFolderD));

    /*
     * create overall histogram and add it to the kmz file
     */
    ScreenOverlayType histogram = createHistogram(transportMode, evacuationTimes);
    mainFolder.getAbstractFeatureGroup().add(kmlObjectFactory.createScreenOverlay(histogram));

    /*
     * create legend and add it to the kmz file
     */
    ScreenOverlayType legend = createLegend(transportMode);
    mainFolder.getAbstractFeatureGroup().add(kmlObjectFactory.createScreenOverlay(legend));

    Map<BasicLocation, List<Double>> locationMap = new HashMap<BasicLocation, List<Double>>();

    for (Entry<Id, BasicLocation> entry : locations.entrySet()) {
        Id id = entry.getKey();
        BasicLocation location = entry.getValue();

        List<Double> list = locationMap.get(location);
        if (list == null) {
            list = new ArrayList<Double>();
            locationMap.put(location, list);
        }

        Double value = evacuationTimes.get(id);
        if (value == null)
            value = Double.NaN;
        list.add(value);
    }

    log.info("Number of different start locations found: " + locationMap.size());

    if (doClustering) {
        EvacuationTimeClusterer clusterer = new EvacuationTimeClusterer(scenario.getNetwork(), locationMap,
                scenario.getConfig().global().getNumberOfThreads());
        int numClusters = (int) Math.ceil(locationMap.size() / clusterFactor);
        locationMap = clusterer.buildCluster(numClusters, clusterIterations);
    }

    for (Entry<BasicLocation, List<Double>> entry : locationMap.entrySet()) {
        BasicLocation location = entry.getKey();
        List<Double> list = entry.getValue();

        int valid = 0;
        int invalid = 0;

        /*
         * Remove NaN entries from the List
         */
        List<Double> listWithoutNaN = new ArrayList<Double>();
        for (Double d : list) {
            if (d.isNaN()) {
                invalid++;
            } else
                listWithoutNaN.add(d);
        }

        /*
         * If trip with significant to high evacuation times should be cut off
         */
        if (limitMaxEvacuationTime) {
            double cutOffValue = meanEvacuationTime + standardDeviation * evacuationTimeCutOffFactor;
            ListIterator<Double> iter = listWithoutNaN.listIterator();
            while (iter.hasNext()) {
                double value = iter.next();
                if (value > cutOffValue) {
                    iter.remove();
                    invalid++;
                }
            }
        }
        valid = list.size() - invalid;

        double mean = 0.0;
        for (Double d : list) {
            mean = mean + d;
        }
        mean = mean / list.size();

        // if at least one valid entry found - otherwise it would result in a divide by zero error
        if (listWithoutNaN.size() == 0)
            continue;
        //         if (invalid < list.size()) mean = mean / (list.size() - invalid);
        //         else continue;

        int index = getColorIndex(mean);

        StyleType styleType = colorBarStyles[index];

        PlacemarkType placemark = createPlacemark(transportMode, location, mean, valid, invalid);
        placemark.setStyleUrl(styleType.getId());
        if (location instanceof Facility) {
            if (valid < 10)
                facilityFolderA.getAbstractFeatureGroup().add(this.kmlObjectFactory.createPlacemark(placemark));
            else if (valid < 100)
                facilityFolderB.getAbstractFeatureGroup().add(this.kmlObjectFactory.createPlacemark(placemark));
            else if (valid < 1000)
                facilityFolderC.getAbstractFeatureGroup().add(this.kmlObjectFactory.createPlacemark(placemark));
            else
                facilityFolderD.getAbstractFeatureGroup().add(this.kmlObjectFactory.createPlacemark(placemark));

        } else if (location instanceof Link) {
            if (valid < 10)
                linkFolderA.getAbstractFeatureGroup().add(this.kmlObjectFactory.createPlacemark(placemark));
            else if (valid < 100)
                linkFolderB.getAbstractFeatureGroup().add(this.kmlObjectFactory.createPlacemark(placemark));
            else if (valid < 1000)
                linkFolderC.getAbstractFeatureGroup().add(this.kmlObjectFactory.createPlacemark(placemark));
            else
                linkFolderD.getAbstractFeatureGroup().add(this.kmlObjectFactory.createPlacemark(placemark));
        } else {
            mainFolder.getAbstractFeatureGroup().add(this.kmlObjectFactory.createPlacemark(placemark));
        }

        histogramToKMZ(transportMode, location, listWithoutNaN);
        boxplotToKMZ(transportMode, location, listWithoutNaN);
    }

    return mainFolder;
}

From source file:marytts.modules.phonemiser.AllophoneSet.java

/**
 * Syllabify a string of allophones. If stress markers are provided, they are preserved; otherwise, primary stress will be
 * assigned to the initial syllable.//from   w w  w . jav  a 2 s  .com
 * <p>
 * The syllabification algorithm itself follows the <i>Core Syllabification Principle (CSP)</i> from <blockquote>G.N. Clements
 * (1990) "The role of the sonority cycle in core syllabification." In: J. Kingston &amp; M.E. Beckman (Eds.),
 * <em>Papers in Laboratory Phonology I: Between the Grammar and Physics of Speech</em>, Ch. 17, pp. 283-333, Cambridge
 * University Press.</blockquote>
 *
 * @param phoneString
 *            phoneString
 * @return a syllabified string; individual allophones are separated by spaces, and syllables, by dashes.
 * @throws IllegalArgumentException
 *             if the <b>phoneString</b> is empty or contains a symbol that satisfies none of the following conditions:
 *             <ol>
 *             <li>the symbol corresponds to an Allophone, or</li> <li>the symbol is a stress symbol (cf. {@link Stress}), or
 *             </li> <li>the symbol is a syllable boundary (<code>-</code>)</li>
 *             </ol>
 * 
 */
public String syllabify(String phoneString) throws IllegalArgumentException {
    // Before we process, a sanity check:
    if (phoneString.trim().isEmpty()) {
        throw new IllegalArgumentException("Cannot syllabify empty phone string");
    }

    // First, split phoneString into a List of allophone Strings...
    List<String> allophoneStrings = splitIntoAllophoneList(phoneString, true);
    // ...and create from it a List of generic Objects
    List<Object> phonesAndSyllables = new ArrayList<Object>(allophoneStrings);

    // Create an iterator
    ListIterator<Object> iterator = phonesAndSyllables.listIterator();

    // First iteration (left-to-right):
    // CSP (a): Associate each [+syllabic] segment to a syllable node.
    Syllable currentSyllable = null;
    while (iterator.hasNext()) {
        String phone = (String) iterator.next();
        try {
            // either it's an Allophone
            Allophone allophone = getAllophone(phone);
            if (allophone.isSyllabic()) {
                // if /6/ immediately follows a non-diphthong vowel, it should be appended instead of forming its own syllable
                boolean appendR = false;
                if (allophone.getFeature("ctype").equals("r")) {
                    // it's an /6/
                    if (iterator.previousIndex() > 1) {
                        Object previousPhoneOrSyllable = phonesAndSyllables.get(iterator.previousIndex() - 1);
                        if (previousPhoneOrSyllable == currentSyllable) {
                            // the /6/ immediately follows the current syllable
                            if (!currentSyllable.getLastAllophone().isDiphthong()) {
                                // the vowel immediately preceding the /6/ is not a diphthong
                                appendR = true;
                            }
                        }
                    }
                }
                if (appendR) {
                    iterator.remove();
                    currentSyllable.appendAllophone(allophone);
                } else {
                    currentSyllable = new Syllable(allophone);
                    iterator.set(currentSyllable);
                }
            }
        } catch (IllegalArgumentException e) {
            // or a stress or boundary marker
            if (!getIgnoreChars().contains(phone)) {
                throw e;
            }
        }
    }

    // Second iteration (right-to-left):
    // CSP (b): Given P (an unsyllabified segment) preceding Q (a syllabified segment), adjoin P to the syllable containing Q
    // iff P has lower sonority rank than Q (iterative).
    currentSyllable = null;
    boolean foundPrimaryStress = false;
    iterator = phonesAndSyllables.listIterator(phonesAndSyllables.size());
    while (iterator.hasPrevious()) {
        Object phoneOrSyllable = iterator.previous();
        if (phoneOrSyllable instanceof Syllable) {
            currentSyllable = (Syllable) phoneOrSyllable;
        } else if (currentSyllable == null) {
            // haven't seen a Syllable yet in this iteration
            continue;
        } else {
            String phone = (String) phoneOrSyllable;
            try {
                // it's an Allophone -- prepend to the Syllable
                Allophone allophone = getAllophone(phone);
                if (allophone.sonority() < currentSyllable.getFirstAllophone().sonority()) {
                    iterator.remove();
                    currentSyllable.prependAllophone(allophone);
                }
            } catch (IllegalArgumentException e) {
                // it's a provided stress marker -- assign it to the Syllable
                switch (phone) {
                case Stress.PRIMARY:
                    iterator.remove();
                    currentSyllable.setStress(Stress.PRIMARY);
                    foundPrimaryStress = true;
                    break;
                case Stress.SECONDARY:
                    iterator.remove();
                    currentSyllable.setStress(Stress.SECONDARY);
                    break;
                case "-":
                    iterator.remove();
                    // TODO handle syllable boundaries
                    break;
                default:
                    throw e;
                }
            }
        }
    }

    // Third iteration (left-to-right):
    // CSP (c): Given Q (a syllabified segment) followed by R (an unsyllabified segment), adjoin R to the syllable containing
    // Q iff has a lower sonority rank than Q (iterative).
    Syllable initialSyllable = currentSyllable;
    currentSyllable = null;
    iterator = phonesAndSyllables.listIterator();
    while (iterator.hasNext()) {
        Object phoneOrSyllable = iterator.next();
        if (phoneOrSyllable instanceof Syllable) {
            currentSyllable = (Syllable) phoneOrSyllable;
        } else {
            String phone = (String) phoneOrSyllable;
            try {
                // it's an Allophone -- append to the Syllable
                Allophone allophone;
                try {
                    allophone = getAllophone(phone);
                } catch (IllegalArgumentException e) {
                    // or a stress or boundary marker -- remove
                    if (getIgnoreChars().contains(phone)) {
                        iterator.remove();
                        continue;
                    } else {
                        throw e;
                    }
                }
                if (currentSyllable == null) {
                    // haven't seen a Syllable yet in this iteration
                    iterator.remove();
                    if (initialSyllable == null) {
                        // haven't seen any syllable at all
                        initialSyllable = new Syllable(allophone);
                        iterator.add(initialSyllable);
                    } else {
                        initialSyllable.prependAllophone(allophone);
                    }
                } else {
                    // append it to the last seen Syllable
                    iterator.remove();
                    currentSyllable.appendAllophone(allophone);
                }
            } catch (IllegalArgumentException e) {
                throw e;
            }
        }
    }

    // if primary stress was not provided, assign it to initial syllable
    if (!foundPrimaryStress) {
        initialSyllable.setStress(Stress.PRIMARY);
    }

    // join Syllables with dashes and return the String
    return StringUtils.join(phonesAndSyllables, " - ");
}

From source file:com.xmobileapp.rockplayer.LastFmEventImporter.java

/*********************************
 * /*  w  w  w .  ja  v a 2  s  .  c  om*/
 * Get Artist Events
 * @throws SAXException 
 * @throws ParserConfigurationException 
 *
 *********************************/
public void getArtistEvents() throws SAXException, ParserConfigurationException {
    /*
     * Initialize Artist Cursor
     */
    artistCursor = ((RockPlayer) context).contentResolver.query(MediaStore.Audio.Artists.EXTERNAL_CONTENT_URI,
            ((RockPlayer) context).ARTIST_COLS, // we should minimize the number of columns
            null, // all albums 
            null, // parameters to the previous parameter - which is null also 
            null // sort order, SQLite-like
    );

    /*
     * Declare & Initialize some vars
     */
    String artistName = null;
    String artistNameFiltered = null;
    String artistConcertFileName = null;
    SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
    SAXParser saxParser = saxParserFactory.newSAXParser();
    XMLReader xmlReader = saxParser.getXMLReader();
    XMLArtistEventHandler xmlHandler = new XMLArtistEventHandler();
    xmlHandler.myLocation = this.myLocation;
    xmlReader.setContentHandler(xmlHandler);

    /*
     * Set Distance Limit
     */
    xmlHandler.MAX_DISTANCE = this.concertRadius;

    /*
     * Loop through the artists
     */
    artistCursor.moveToFirst();
    for (int i = 0; i < artistCursor.getCount(); i++) {
        /*
         * Get artist name
         */
        artistName = artistCursor.getString(artistCursor.getColumnIndex(MediaStore.Audio.Artists.ARTIST));
        if (artistName.equals("<unknown>")) {
            artistCursor.moveToNext();
            continue;
        }
        artistNameFiltered = filterString(artistName);
        artistConcertFileName = ((RockPlayer) context).FILEX_CONCERT_PATH + validateFileName(artistName);

        /*
         * UI feedback
         */
        Bundle data = new Bundle();
        data.putString("info", artistName);
        Message msg = new Message();
        msg.setData(data);
        ((RockPlayer) context).analyseConcertInfoHandler.sendMessage(msg);

        /*
         * If we dont have yet or info is too old, update the concert info of this artist
         */
        if (hasConcertInfo(artistName) == false || concertInfoNeedsUpdate(artistName) == true) {
            Log.i("INET", "Getting concert info from LastFM");
            if (hasConcertInfo(artistName) == false)
                Log.i("INET", "Because there is no concert info yet");
            if (concertInfoNeedsUpdate(artistName) == true)
                Log.i("INET", "Because Info is too old");

            File artistConcertFile = new File(artistConcertFileName);
            if (!artistConcertFile.exists()) {
                try {
                    artistConcertFile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            URL lastFmApiRequest;
            try {
                lastFmApiRequest = new URL(
                        this.LAST_FM_API_URL + "&artist=" + URLEncoder.encode(artistNameFiltered));
                BufferedInputStream bufferedURLStream = new BufferedInputStream(lastFmApiRequest.openStream());
                BufferedOutputStream bufferedFileWriter = new BufferedOutputStream(
                        new FileOutputStream(artistConcertFile));

                byte[] buf = new byte[1024];
                int len;
                while ((len = bufferedURLStream.read(buf)) >= 0)
                    bufferedFileWriter.write(buf, 0, len);
                bufferedURLStream.close();
                bufferedFileWriter.close();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        /*
         * get event list from cached XML files
         */
        File artistConcertFile = new File(artistConcertFileName);
        if (artistConcertFile.exists() && artistConcertFile.length() > 0) {
            try {
                BufferedReader xmlFileReader = new BufferedReader(
                        new InputStreamReader(new FileInputStream(artistConcertFile)));
                xmlHandler.resetList();
                xmlHandler.artist = artistName;
                xmlReader.parse(new InputSource(xmlFileReader));
                insertListInListByDate(xmlHandler.artistEventList);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (SAXException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        artistCursor.moveToNext();
    }

    /*
     * Debug
     */
    ArtistEvent artistEventDebug = null;
    if (!artistEventList.isEmpty()) {
        artistEventList.getFirst();
        ListIterator<ArtistEvent> listIterator = artistEventList.listIterator(0);
        for (artistEventDebug = listIterator.next(); listIterator
                .hasNext() == true; artistEventDebug = listIterator.next()) {
            if (artistEventDebug != null)
                Log.i("DBG", artistEventDebug.date + " " + artistEventDebug.city);
            //   Log.i("DBG", artistEventDebug.date+" "+artistEventDebug.city+" "+artistEventDebug.artist);
            else
                Log.i("DBG", "NULL");
        }
    }
    /*
     * Update Adapter
     */
    eventLinkedListAdapter = new EventLinkedListAdapter(context, R.layout.eventlist_item, artistEventList);
    if (eventLinkedListAdapter == null)
        Log.i("NULL", "NULL");
    ((RockPlayer) context).updateEventListHandler.sendEmptyMessage(0);

    /*
     * Give feedback to the user
     */
    Bundle data = new Bundle();
    Message msg = new Message();
    data.putString("info", "Done!");
    msg.setData(data);
    ((RockPlayer) context).analyseConcertInfoHandler.sendMessage(msg);
}