Java Code Examples for java.util.Vector

The following are top voted examples for showing how to use java.util.Vector. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: jentrata-msh   File: PropertyTree.java View source code Vote up 6 votes
/**
 * Gets all the existing property xpaths.
 * 
 * @return all the existing property xpaths.
 * @see hk.hku.cecid.piazza.commons.util.PropertySheet#propertyNames()
 */
public Enumeration propertyNames() {
    Iterator nodes = getPropertyNodes("//*[count(./*)=0]").iterator();
    Vector propNames = new Vector();

    while (nodes.hasNext()) {
        Node node = (Node) nodes.next();
        propNames.addElement(node.getUniquePath());
    }

    return propNames.elements();
}
 
Example 2
Project: dlna   File: HttpServer.java View source code Vote up 6 votes
/**
 * Find the byte positions where multipart boundaries start.
**/
public int[] getBoundaryPositions(byte[] b, byte[] boundary)
{
	int matchcount = 0;
	int matchbyte = -1;
	Vector matchbytes = new Vector();
	for (int i=0; i<b.length; i++)
	{
		if (b[i] == boundary[matchcount])
		{
			if (matchcount == 0)
				matchbyte = i;
			matchcount++;
			if (matchcount==boundary.length)
			{
				matchbytes.addElement(new Integer(matchbyte));
				matchcount = 0;
				matchbyte = -1;
			}
		}
		else
		{
			i -= matchcount;
			matchcount = 0;
			matchbyte = -1;
		}
	}
	int[] ret = new int[matchbytes.size()];
	for (int i=0; i < ret.length; i++)
	{
		ret[i] = ((Integer)matchbytes.elementAt(i)).intValue();
	}
	return ret;
}
 
Example 3
Project: aipo   File: JetspeedDaemonFactoryService.java View source code Vote up 6 votes
/**
 * Perform initialization of the DaemonFactory. Note that this should return
 * right away so that processing can continue (IE thread off everything)
 */
public synchronized void init(ServletConfig config) {

  // already initialized
  if (getInit())
    return;

  logger.info("Early init for DaemonFactory called...");

  this.context = new DaemonContext();

  // init daemons from config file
  Vector raw = JetspeedResources.getVector(JetspeedResources.DAEMON_ENTRY);
  this.entries = new DaemonEntry[raw.size()];

  for (int i = 0; i < raw.size(); ++i) {

    String name = (String) raw.elementAt(i);
    String classname = JetspeedResources.getString("daemon." + name
        + ".classname");
    long interval = JetspeedResources.getLong("daemon." + name + ".interval");
    boolean onstartup = JetspeedResources.getBoolean("daemon." + name
        + ".onstartup");

    entries[i] = new DaemonEntry(name, interval, classname, onstartup);

  }

  setInit(true);
  logger.info("Early init for DaemonFactory done");

  // Finish by starting requested Daemons...
  this.start();
}
 
Example 4
Project: SafariBowl   File: RuleThrow.java View source code Vote up 6 votes
protected void askForInterception(SBProtocolMessage message, Vector2d destinationField, int throwModificator) {
	Vector<Player> possibleInterceptors = findPossibleInterceptors(actor, destinationField);
	if(possibleInterceptors.size() == 0){
		throwBall(message, destinationField, throwModificator);
	}else{
		Vector<String> parameters = new Vector<String>();
		parameters.add(SBProtocolMessage.EVENT_API_CHOICE);
		parameters.add(SBProtocolMessage.EVENT_ASK_FOR_INTERCEPTOR);
		for(Player player:possibleInterceptors){
			if(player.getTeam() == getMatch().getTeam(0)){
				parameters.add("0");
				parameters.add((player.getId()-1) + "");
			}else if(player.getTeam() == getMatch().getTeam(1)){
				parameters.add("1");
				parameters.add((player.getId()-1) + "");
			}
		}
		String[] parameterArray = parameters.toArray(new String[parameters.size()]);
		((ServerMatch)getMatch()).setCurrentModificatorWaitingForAnser(throwModificator);
		((ServerMatch)getMatch()).setCurrentDefenderFieldWaitingForAnswer(destinationField);
		((ServerMatch)getMatch()).setCurrentMessageWaitingForAnswer(message);
		((ServerMatch)getMatch()).setCurrentActorWaitingForAnswer(actor);
		getMatch().setGamePhase(5);
		sendMessage(getMatch().getOpponent(actor.getTeam().getCoach()), SBProtocolCommand.EVENT, parameterArray);
	}
}
 
Example 5
Project: aipo   File: BaseSecurityAccess.java View source code Vote up 6 votes
/**
 * Return a vector contain all allows elements.  If the vector is null
 * or empty, then create and populate it with elements from the allows
 * and ownerAllows vectors.
 *
 * @return vector containing all allows
 */
public Vector getAllAllows()
{
    int elementCount = 0;
    if (this.allAllows == null)
    {
        allAllows = new Vector();
    }

    if (allAllows.isEmpty() == true)
    {
        if (this.allows != null)
        {
            elementCount += this.allows.size();
            allAllows.ensureCapacity(elementCount);
            allAllows.addAll(this.allows);
        }

        if (this.ownerAllows != null)
        {
            elementCount += this.ownerAllows.size();
            allAllows.ensureCapacity(elementCount);
            allAllows.addAll(this.ownerAllows);
        }
    }
    return this.allAllows;
}
 
Example 6
Project: aipo   File: URLFetcher.java View source code Vote up 6 votes
/**
Add a URL that is downloading in realtime
*/
static final void addRealtimeURL( String url ) {
    synchronized( realtime_urls )
    {
        Vector threads = (Vector) realtime_urls.get( url);
        if(threads != null)
           {
            if(!threads.contains(Thread.currentThread()))
               {
                 threads.addElement(Thread.currentThread() );
               }
           } else {
            threads = new Vector();
            threads.addElement(Thread.currentThread());
            realtime_urls.put( url, threads  );
           }
    }
    
}
 
Example 7
Project: jena   File: testWriterAndReader.java View source code Vote up 6 votes
public void testOptions() throws IOException 
      {
Vector<Resource> v = new Vector<>();
for (int i = 0; i < blockRules.length; i += 1) 
          {
	if ((options & (1 << i)) != 0) v.add( blockRules[i] );
          }
Resource blocked[] = new Resource[v.size()];
v.copyInto( blocked );
doTest( new String[] { "blockRules" }, new Resource[][] { blocked } );
      }
 
Example 8
Project: speechalyzer   File: OpenEarExtractor.java View source code Vote up 6 votes
public void extractAllFeatures(AudioFileManager afm, boolean append) {
	long timeTaken = 0;
	Vector<RecFile> audioFiles;
	if (append) {
		audioFiles = afm.getAudioFilesWithoutPredictions();
	} else {
		audioFiles = afm.getAudioFiles();
		new File(_trainFileName).delete();
	}
	for (Iterator<RecFile> iterator = audioFiles.iterator(); iterator
			.hasNext();) {
		RecFile recFile = (RecFile) iterator.next();
		String audioFile = checkFileName(recFile._path);
		String command = _openEarCommandName + " -C " + _openEarConfigName
				+ " -I " + audioFile + " -O " + _trainFileName
				+ " -classlabel " + recFile.getStringLabel();
		Util.printOut(".", false);
		try {
			long startTime = System.currentTimeMillis();
			Util.execCmd(command, _logger);
			timeTaken += System.currentTimeMillis() - startTime;
		} catch (Exception e) {
			e.printStackTrace();
			_logger.error(e.getMessage());
		}
		System.out.print(".");
	}
	System.out.println();
	_logger.info("featureExtraction of " + audioFiles.size()
			+ " files took " + timeTaken / 1000.0 + " seconds");
}
 
Example 9
Project: NewsSpeakServer   File: ConnectionManager.java View source code Vote up 6 votes
/**
 * Add qualified cookies from cookies into list.
 * @param cookies The list of cookies to check (may be null).
 * @param path The path being accessed.
 * @param list The list of qualified cookies.
 * @return The list of qualified cookies.
 */
protected Vector addCookies (Vector cookies, String path, Vector list)
{
    Cookie cookie;
    Date expires;
    Date now;

    if (null != cookies)
    {
        now = new Date ();
        for (int i = 0; i < cookies.size (); i++)
        {
            cookie = (Cookie)cookies.elementAt (i);
            expires = cookie.getExpiryDate ();
            if ((null != expires) && expires.before (now))
            {
                cookies.remove (i);
                i--; // dick with the loop variable
            }
            else
                if (path.startsWith (cookie.getPath ()))
                {
                    if (null == list)
                        list = new Vector ();
                    list.addElement (cookie);
                }
        }
    }
    
    return (list);
}
 
Example 10
Project: bbssh   File: MacroEditorScreen.java View source code Vote up 6 votes
private void editAction(int idx) {
	Vector commands = macro.getCommandVector();
	PersistableCommandFactory pf = (PersistableCommandFactory) commands.elementAt(partsList.getSelectedIndex());
	KeybindState state = new KeybindState(-1, "Edit Macro Action",
			KeyBindingManager.getInstance().getExecutableCommandById(pf.getExecutableCommandId()),
			pf.getParam());
	popup.setKeybindState(state);
	UiApplication.getUiApplication().pushModalScreen(popup);
	if (popup.isChangeSaved()) {
		state.changed = true;
		commands.insertElementAt(new PersistableCommandFactory(0, state.command.getId(), state.parameter), idx);
		commands.removeElementAt(idx + 1);
	}
	enableControlsForSelection(true);

}
 
Example 11
Project: aipo   File: URLFetcher.java View source code Vote up 6 votes
/**
Remove a URL because it isn't downloading anymore.
*/
static final void removeRealtimeURL( String url ) {
    synchronized( realtime_urls )
    {
       Vector threads = (Vector) realtime_urls.get( url);
       if(threads != null)
           synchronized( threads  )
               {
                Thread realLoader = (Thread) threads.firstElement();
                if(realLoader == Thread.currentThread())
                {
                  synchronized(url.intern())
                 {
                  realtime_urls.remove(url);
                  url.intern().notifyAll();
                  }          
                 } else {
                 threads.removeElement(Thread.currentThread());
                 }
                }
    }
    
}
 
Example 12
Project: ISODonosti   File: GestorOfertas.java View source code Vote up 6 votes
/**
 * Mtodo para ordenar un vector de ofertas por das
 * 
 * @param izq, extremo izquierdo del vector
 * @param der, extremo derecho del vector
 * @param a, vector de ofertas
 * @return vector de ofertas ordenadas
 */
public Vector quickSort_Dias(int izq, int der, Vector a) {
	//ordena de mayor a menor
	if (a == null || a.isEmpty())
		return a;
	int i = izq;
	int j = der;
	Oferta of = (Oferta) a.elementAt((izq + der) / 2);
	long pivote = of.getDiaFin().getTime() -  of.getDiaIni().getTime();
	do {
		while (((Oferta)a.elementAt(i)).getDiaFin().getTime() - (((Oferta) a.elementAt(i)).getDiaIni().getTime()) > pivote)
			i++;
		while (((Oferta) a.elementAt(j)).getDiaFin().getTime() - (((Oferta) a.elementAt(j)).getDiaIni().getTime()) < pivote)
			j--;
		if (i <= j) {
			Oferta aux = (Oferta) a.elementAt(i);
			a.setElementAt(a.elementAt(j), i);
			a.setElementAt(aux, j);
			i++;
			j--;
		}
	} while (i <= j);
	if (izq < j)
		quickSort_Dias(izq, j, a);
	if (i < der)
		quickSort_Dias(i, der, a);
	return a;
}
 
Example 13
Project: fiji   File: AmiraParameters.java View source code Vote up 6 votes
void initializeMaterials() {
	if(materials==null)
		materials=new Vector();
	String list=(String)parameters.get("MaterialList");
	if(list==null) {
		list="";
		for(int i=0;i<materials.size();i++)
			list+=(i>0?",":"")+(String)materials.get(i);
		parameters.put("MaterialList",list);
	} else {
		materials.clear();
		StringTokenizer t=new StringTokenizer(list,",");
		while(t.hasMoreTokens())
			materials.add(t.nextToken());
	}
}
 
Example 14
Project: JFugue-for-Android   File: AttributeMap.java View source code Vote up 6 votes
/**
 * Override parent's method to set the ownerNode correctly
 */
protected void cloneContent(NamedNodeMapImpl srcmap) {
    Vector srcnodes = srcmap.nodes;
    if (srcnodes != null) {
        int size = srcnodes.size();
        if (size != 0) {
            if (nodes == null) {
                nodes = new Vector(size);
            }
            nodes.setSize(size);
            for (int i = 0; i < size; ++i) {
                NodeImpl n = (NodeImpl) srcnodes.elementAt(i);
                NodeImpl clone = (NodeImpl) n.cloneNode(true);
                clone.isSpecified(n.isSpecified());
                nodes.setElementAt(clone, i);
                clone.ownerNode = ownerNode;
                clone.isOwned(true);
            }
        }
    }
}
 
Example 15
Project: bbssh   File: DefaultSyncCollection.java View source code Vote up 6 votes
public final boolean updateSyncObject(SyncObject oldObject, SyncObject newObject) {
	Vector dv = getDataVector(); // using the getter ensures that it loads.
	int idx = dv.indexOf(oldObject);
	if (idx == -1) {
		return false;
	}
	dv.setElementAt(newObject, idx);
	return true;
}
 
Example 16
Project: ISODonosti   File: TestGestorOfertas.java View source code Vote up 6 votes
/**
 * En esta prueba se concatenan 2 ofertas 
 */
public void test_Concatenar_2_Ofertas(){
	
	//Entrada
	Vector entrada = new Vector();

	Oferta o1 = new Oferta();
	o1.setNumCasa(1);
	o1.setDiaIni(new Date((new GregorianCalendar(2007, 2, 1)).getTime().getTime()));
	o1.setDiaFin(new Date((new GregorianCalendar(2007, 2, 3)).getTime().getTime()));
	o1.setPrecio(300);
	
	Oferta o2 = new Oferta();
	o2.setNumCasa(1);
	o2.setDiaIni(new Date((new GregorianCalendar(2007, 2, 3)).getTime().getTime()));
	o2.setDiaFin(new Date((new GregorianCalendar(2007, 2, 7)).getTime().getTime()));
	o2.setPrecio(200);
	
	entrada.add(o1);
	entrada.add(o2);

	//Resultado Esperado
	Vector esperado = (Vector)entrada.clone();
	Oferta o3 = new Oferta();
	o3.setNumCasa(1);
	o3.setDiaIni(new Date((new GregorianCalendar(2007, 2, 1)).getTime().getTime()));
	o3.setDiaFin(new Date((new GregorianCalendar(2007, 2, 7)).getTime().getTime()));
	o3.setPrecio(500);		
	esperado.add(o3);
	
	//Ejecutar test
	Vector obtenido = (Vector)gestorOfertas.concatenarOfertas(entrada);
	assertEquals("Error en la concatenacion!", esperado, obtenido);	
}
 
Example 17
Project: JFugue-for-Android   File: DeepNodeListImpl.java View source code Vote up 6 votes
/** Returns the node at the specified index. */
public Node item(int index) {
	Node thisNode;

    // Tree changed. Do it all from scratch!
	if(rootNode.changes() != changes) {
        nodes   = new Vector();     
        changes = rootNode.changes();
	}

    // In the cache
	if (index < nodes.size())      
	    return (Node)nodes.elementAt(index);

    // Not yet seen
	else {

        // Pick up where we left off (Which may be the beginning)
		if (nodes.size() == 0)     
		    thisNode = rootNode;
		else
		    thisNode=(NodeImpl)(nodes.lastElement());

		// Add nodes up to the one we're looking for
		while(thisNode != null && index >= nodes.size()) {
			thisNode=nextMatchingElementAfter(thisNode);
			if (thisNode != null)
			    nodes.addElement(thisNode);
		    }

        // Either what we want, or null (not avail.)
  return thisNode;           
 }

}
 
Example 18
Project: Citation-Application   File: CLocation.java View source code Vote up 6 votes
public CLocation() { 
	setReadOnly(false);
    _elements = new Vector(ELEMENT_COUNT);
    for (int i = 0; i < _elements.capacity(); ++i) {
        _elements.addElement(new String(""));
    }
}
 
Example 19
Project: aipo   File: UserRoleUpdateAction.java View source code Vote up 6 votes
/**
 * Build the context for a role browser for a specific user.
 *
 * @param portlet The velocity-based portlet that is being built.
 * @param context The velocity context for this request.
 * @param rundata The turbine rundata context for this request.
 * @param userid The userid of the user that we are building a role context for.
 */
private void buildUserRoleContext(VelocityPortlet portlet,
                                   Context context,
                                   RunData rundata,
                                   String userid)
    throws Exception
{
    // get the user object
    JetspeedUser user = JetspeedSecurity.getUser(userid);
    if (null == user)
    {
        // no User found
        logger.error("UserRoleBrowser: Failed to get user: " + userid );
        return;
    }
    // get master list of roles
    Iterator roles = JetspeedSecurity.getRoles();
    Vector masterRoles = new Vector();
    Vector selected = new Vector();
    int ix = 0;
    boolean sel = false;
    selected.add(ix, new Boolean(sel));
    while(roles.hasNext())
    {
        Role role = (Role)roles.next();
        //System.out.println("In buildUserRoleContext role="+role.getName());
        masterRoles.add(role);
        sel = JetspeedSecurity.hasRole(user.getUserName(), role.getName());
        //System.out.println("In buildUserRoleContext sel="+sel);
        ix = ix + 1;
        selected.add(ix, new Boolean(sel));
    }
    masterRoles.trimToSize();
    selected.trimToSize();

    rundata.getUser().setTemp(SecurityConstants.CONTEXT_ROLES, masterRoles);
    rundata.getUser().setTemp(SecurityConstants.CONTEXT_SELECTED, selected);
    context.put(SecurityConstants.CONTEXT_USER, user);
    context.put(SecurityConstants.CONTEXT_ROLES, masterRoles);
    context.put(SecurityConstants.CONTEXT_SELECTED, selected);

}
 
Example 20
Project: JBossAS_5_1_EDG   File: ClusterPartition.java View source code Vote up 6 votes
/**
 * Helper method that returns a vector of dead members from two input vectors: new and old vectors of two views.
 * Dead members are old - new members.
 * @param oldMembers Vector of old members
 * @param newMembers Vector of new members
 * @return Vector of members that have died between the two views, can be empty.
 */
protected Vector<ClusterNode> getDeadMembers(Vector<ClusterNode> oldMembers, Vector<ClusterNode> newMembers)
{
   if(oldMembers == null)
   {
      oldMembers=new Vector<ClusterNode>();
   }
   if(newMembers == null)
   {
      newMembers=new Vector<ClusterNode>();
   }
   Vector<ClusterNode> dead=(Vector<ClusterNode>)oldMembers.clone();
   dead.removeAll(newMembers);
   this.log.debug("dead members: " + dead);
   return dead;
}
 
Example 21
Project: jxta   File: RouteAdvertisement.java View source code Vote up 6 votes
/**
 * [email protected]}
 */
@Override
public RouteAdvertisement clone() {
    try {
        RouteAdvertisement a = (RouteAdvertisement) super.clone();

        a.setDest(getDest());

        // deep copy of the hops
        Vector<AccessPointAdvertisement> clonehops = getVectorHops();

        ListIterator<AccessPointAdvertisement> eachHop = clonehops.listIterator();

        while (eachHop.hasNext()) {
            eachHop.set(eachHop.next().clone());
        }

        a.setHops(clonehops);

        return a;
    } catch (CloneNotSupportedException impossible) {
        throw new Error("Object.clone() threw CloneNotSupportedException", impossible);
    }
}
 
Example 22
Project: netlib   File: CircuitAdmin.java View source code Vote up 5 votes
/**
 * used to return a number of circuits to a target. established a new circuit or uses an existing one
 *
 * @param sp gives some basic restrains
 * @param forHiddenService if set to true, use circuit that is unused and don't regard exit-policies
 */
public static Circuit[] provideSuitableCircuits(
        TLSConnectionAdmin tlsConnectionAdmin, Directory dir, TCPStreamProperties sp, TorEventService torEventService, boolean forHiddenService)
throws IOException {
    log.fine("TLSConnectionAdmin.provideSuitableCircuits: called for " + sp.getHostname());
    
    // TODO test: shortcut/cache
    Circuit[] cachedResults = suitableCircuitsCache.get(sp.getHostname());
    if (cachedResults != null) {
        // TODO return cachedResults;
    }

    // list all suiting circuits in a vector
    int numberOfExistingCircuits = 0;
    Vector<Circuit> allCircs = new Vector<Circuit>(10, 10);
    int rankingSum = 0;
    for (TLSConnection tls : tlsConnectionAdmin.getConnections()) {
        for (Circuit circuit : tls.getCircuits()) {
            try {
                ++numberOfExistingCircuits;
                if (circuit.isEstablished() && (!circuit.isClosed()) && DirectoryService.isCompatible(dir, circuit, sp, forHiddenService)) {
                    allCircs.add(circuit);
                    rankingSum += circuit.getRanking();
                }
            } catch (TorException e) { /* do nothing, just try next circuit */ }
        }
    }
    // sort circuits (straight selection... O(n^2)) by
    // - whether they contained a stream to the specific address
    // - ranking (stochastically!)
    // - implicit: whether they haven't had a stream at all
    for (int i = 0; i < allCircs.size() - 1; ++i) {
        Circuit c1 = (Circuit) allCircs.get(i);
        int min = i;
        int minRanking = c1.getRanking();
        if (minRanking == 0) {
            minRanking = 1;
        }
        boolean minPointsToAddr = c1.getStreamHistory().contains(sp.getHostname());
        for (int j = i + 1; j < allCircs.size(); ++j) {
            Circuit thisCirc = (Circuit) allCircs.get(j);
            int thisRanking = thisCirc.getRanking();
            if (thisRanking == 0) {
                thisRanking = 1;
            }
            boolean thisPointsToAddr = thisCirc.getStreamHistory().contains(sp.getHostname());
            float rankingQuota = thisRanking / minRanking;
            if ((thisPointsToAddr && !minPointsToAddr)|| (TLSConnectionAdmin.rnd.nextFloat() > Math.exp(-rankingQuota))) {
                // sort stochastically
                min = j;
                minRanking = thisRanking;
            }
        }
        if (min > i) {
            Circuit temp = allCircs.set(i, allCircs.get(min));
            allCircs.set(min, temp);
        }
    }
    // return number of circuits suiting to number of stream-connect retries!
    int returnValues = sp.getConnectRetries();
    if (allCircs.size() < returnValues) {
        returnValues = allCircs.size();
    }
    if ((returnValues == 1) && (numberOfExistingCircuits < TorConfig.circuitsMaximumNumber)) {
        // spawn new circuit IN BACKGROUND, unless maximum number of
        // circuits reached
        log.fine("TLSConnectionAdmin.provideSuitableCircuits: spawning circuit to " + sp.getHostname() + " in background");
        Thread spawnInBackground = new NewCircuitThread(tlsConnectionAdmin, dir, sp, torEventService);
        spawnInBackground.setName("CuircuitAdmin.provideSuitableCircuits");
        spawnInBackground.start();
    } else if ((returnValues == 0) && (numberOfExistingCircuits < TorConfig.circuitsMaximumNumber)) {
        // spawn new circuit, unless maximum number of circuits reached
        log.fine("TLSConnectionAdmin.provideSuitableCircuits: spawning circuit to " + sp.getHostname());
        Circuit single = provideSuitableNewCircuit(tlsConnectionAdmin, dir, sp, torEventService);
        if (single != null) {
            returnValues = 1;
            allCircs.add(single);
        }
    }
    // copy values
    Circuit[] results = new Circuit[returnValues];
    for (int i = 0; i < returnValues; ++i) {
        results[i] = (Circuit) allCircs.get(i);
        if (log.isLoggable(Level.FINE)) {
            log.fine("TLSConnectionAdmin.provideSuitableCircuits: Choose Circuit ranking " + results[i].getRanking() + ":" + results[i].toString());
        }
    }

    // TODO gri test: shortcat/cache
    suitableCircuitsCache.put(sp.getHostname(), results);

    return results;
}
 
Example 23
Project: aipo   File: JetspeedContentAdmin.java View source code Vote up 5 votes
/**
*/
public synchronized ConcreteElement postArticle( String provider, RunData rundata ) {
    ElementContainer ec = new ElementContainer();

    ParameterParser params = rundata.getParameters();        
    
    String topic = params.getString( "topic", "" );
    String title = params.getString( "title", "" );
    String link  = params.getString( "link", "" );
    String description  = params.getString( "description", "" );
    
    //create the JCM item
    Item item = new Item();
    item.setTopic( topic );
    item.setTitle( title );
    item.setLink( link );
    item.setDescription( description );
    

    Content content = null;
    try {
        content = this.getContentMarkup( this.getURL( provider ) ).getContent();


        //BEGIN reorg of the item list so that the new entry begins at the top
        Vector v = new Vector();
        
        Item[] items = content.getChannel().getItem();
        
        for ( int i = 0; i < items.length; ++i ) {
            v.addElement( items[i] );
        }

        v.insertElementAt( item, 0 );
        
        //now build this into a new array
        
        Item[] newItems = new Item[ v.size() ];
        v.copyInto( newItems );
        
        content.getChannel().removeAllItem();
        
        //now go through all the new items and add those
        for ( int i = 0; i < newItems.length; ++i ) {
            content.getChannel().addItem( newItems[i] );
        }

        //END reorg of the item list so that the new entry begins at the top            
        
        //save the portlet markup after you have made the changes.
        this.getContentMarkup( this.getURL( provider ) ).save();

    } catch ( Throwable t ) {
        logger.error("Throwable", t);
        return new StringElement( "Can't use this provider: " + t.getMessage() );
    }
    
    ec.addElement( "Your article '" + title + "' has been posted within '" + topic + "'" );
    
    return ec;
}
 
Example 24
Project: grap   File: XYZ2DEM_Importer.java View source code Vote up 5 votes
public void read(String path) {

		if (IJ.versionLessThan("1.31a"))
			return;

		double tol = 1.e-20;
		tol = initializeTolerance(tol); // Approximate machine-epsilon

		// Read XYZ coordinates from text file
		Vector coordinateList = new Vector();

		try {
			Reader r = new BufferedReader(new InputStreamReader(
					new FileInputStream(path)));
			parseCoordinatesFromTextfile(r, coordinateList);
			IJ.showStatus("XYZ_Import " + Integer.toString(numberOfPoints)
					+ " points");

			r.close();
			// IJ.showStatus("XYZ_Import input: " + path);
		} catch (IOException e) {
			String msg = e.getMessage();
			if (msg == null || msg.equals(""))
				msg = "" + e;
			IJ.showMessage("XYZ_Import", msg);
		}

		// Initialize coordinate arrays:
		double[] xVcl = new double[(numberOfPoints + 4)]; // X coordinates
		// (input) (xVcl[0]
		// is not used)
		double[] yVcl = new double[(numberOfPoints + 4)]; // Y coordinates
		// (input) (yVcl[0]
		// is not used)
		double[] zVcl = new double[(numberOfPoints + 4)]; // Z coordinates
		// (input) (zVcl[0]
		// is not used)
		copyCoordinatesToArrays(coordinateList, xVcl, yVcl, zVcl);
		coordinateList.removeAllElements();

		// Initialize arrays for the triangulation:
		int[] ind = new int[numberOfPoints + 4]; // Index of sorted X/Y
		// coordinates (ind[0] is
		// not used)
		int[][] til = new int[3][2 * (numberOfPoints + 4) + 2]; // List of
		// triangles
		// (til[][0] is
		// not used)
		int[][] tnbr = new int[3][2 * (numberOfPoints + 4) + 2]; // List of
		// neighbour
		// triangles
		// (tnbr[][0]
		// is not
		// used)
		int[] stack = new int[2 * (numberOfPoints + 4) + 2]; // Stack of
		// triangles for
		// which
		// circumcircle
		// test must be
		// made
		// (stack[0] is
		// not used)
		// Later used to mark triangles to be disregarded (myMaximumEdgeLength)

		// Initialize index, sort points, eliminate point doublets (in X and Y):
		sortAndCheckCoordinates(xVcl, yVcl, zVcl, ind, stack, tol);
		if (numberOfPoints < 3) {
			IJ.showMessage("XYZ_Import",
					"ERROR: Number of points is less than three!");
			IJ.showStatus("");
			return;
		}

		userinput();

		// Transform coordinates and perform Delaunay-Triangulation:
		IJ.showStatus("XYZ_Import builds up mesh");
		IJ.showProgress(0.0);
		setImageBoundary(tol);
		transformCoordinates(xVcl, yVcl);
		if (myShowLimitsDecision)
			userShowLimits(); // Write boundary information to text file

		int ierr = 0;
		ierr = delaunayTriangulation(xVcl, yVcl, ind, til, tnbr, stack, tol);
		if (ierr == 8) {
			IJ
					.showMessage(
							"XYZ_Import",
							"ERROR: Not enough space in 'stack' array.\n \n"
									+ "(This error should not occur. Please give feedback to the author.)");
			return;
		} else if (ierr == 225) {
			IJ
					.showMessage("XYZ_Import",
							"ERROR: All points are collinear (in floating point arithmetic).");
			return;
		}

		// Initialize resulting image:
		IJ.showStatus("XYZ_Import generates 32-bit image");
		IJ.showProgress(0.0);

		int za = boundaryOfImageCoordSysImage[2] + 1;
		int sa = boundaryOfImageCoordSysImage[1] + 1;

		rastermetadata = new RasterMetadata(boundaryOfXYZCoordSysXYZ[0],
				boundaryOfXYZCoordSysXYZ[3], (float) myPixelSize,
				(float) -myPixelSize, boundaryOfImageCoordSysImage[1],
				boundaryOfImageCoordSysImage[2], (float) myBackground);

		System.out.println(rastermetadata.getEnvelope());

		ip = new FloatProcessor(sa, za);
		float[] myPixelValues = (float[]) ip.getPixels();

		// Perform image interpolation (linear interpolation within a triangle):
		interpolateImageLinear(til, tnbr, xVcl, yVcl, zVcl, stack,
				myPixelValues, tol);

		// Adjust brightness and contrast:
		ip.resetMinAndMax();

	}
 
Example 25
Project: aipo   File: ParameterLoader.java View source code Vote up 5 votes
/**
 * Pulls out an instance of the object by name.  Name is just the
 * single name of the object.
 * 
 * @param provider   Name of object instance.
 * @return A Screen with the specified name, or null.
 * @exception Exception a generic exception.
 */
public ParameterPresentationStyle getInstance(String provider) throws Exception {

    ParameterPresentationStyle prm = null;

    // Check if the parameter is already in the cache
    if (cache() && this.containsKey(provider)) {

        prm = (ParameterPresentationStyle) this.get(provider);
        if ( logger.isDebugEnabled() ) {
            logger.debug("ParameterLoader: Serving parameter: " + provider + ", prm=" + prm + " from cache");            
        }

    } else {

        // We get the broker service
        AssemblerBrokerService ab =
            (AssemblerBrokerService)TurbineServices.getInstance()
            .getService (AssemblerBrokerService.SERVICE_NAME);

        try {
            // Attempt to load the presentation style
            prm = (ParameterPresentationStyle)ab.getAssembler("parameter", provider);
            if (prm == null) {
                if ( logger.isDebugEnabled() ) {
                    logger.debug("ParameterLoader: Registering the factory");
                }
                ab.registerFactory("parameter", new ParameterPresentationStyleFactory());
                prm = (ParameterPresentationStyle)ab.getAssembler("parameter", provider);
            }
            if ( logger.isDebugEnabled() ) {
                logger.debug("ParameterLoader: Loaded parameter: "+provider+", prm="+prm);
            }
        } catch (ClassCastException cce) {
            prm = null;
            logger.error( "Error loading presentation style", cce );
        }

        if (prm == null) {
            // If we did not find a screen we should try and give
            // the user a reason for that...
            // FIX ME: The AssemblerFactories should each add it's own string here...
            Vector packages = JetspeedResources.getVector("module.packages");

            throw new ClassNotFoundException( "\n\n\tRequested Parameter not found: " +
                                              provider + "\n" +
                                              "\tTurbine looked in the following modules.packages path: \n\t" +
                                              packages.toString() + "\n");
        } else if(cache()) {

            addInstance(provider, prm);
        }

    }

    return prm;
}
 
Example 26
Project: tdq-studio-se   File: Grid.java View source code Vote up 5 votes
/**
 * Updates cell selection.
 *
 * @param newCell newly clicked, navigated to cells.
 * @param stateMask statemask during preceeding mouse or key event.
 * @param dragging true if the user is dragging.
 * @param reverseDuplicateSelections true if the user is reversing selection rather than adding to.
 *
 * @return selection event that will need to be fired or null.
 */
private Event updateCellSelection(Vector newCells, int stateMask, boolean dragging, boolean reverseDuplicateSelections)
{
    boolean shift = false;
    boolean ctrl = false;

    if ((stateMask & SWT.MOD2) == SWT.MOD2)
    {
        shift = true;
    }
    else
    {
        shiftSelectionAnchorColumn = null;
        shiftSelectionAnchorItem = null;
    }

    if ((stateMask & SWT.MOD1) == SWT.MOD1)
    {
        ctrl = true;
    }

    if (!shift && !ctrl)
    {
        if (newCells.equals(selectedCells)) return null;

        selectedCells.clear();
        for (int i = 0; i < newCells.size(); i++)
        {
            addToCellSelection((Point)newCells.get(i));
        }

    }
    else if (shift)
    {

        Point newCell = (Point)newCells.get(0); //shift selection should only occur with one
        //cell, ignoring others

        if ((focusColumn == null) || (focusItem == null))
        {
            return null;
        }

        shiftSelectionAnchorColumn = getColumn(newCell.x);
        shiftSelectionAnchorItem = getItem(newCell.y);

        if (ctrl)
        {
            selectedCells.clear();
            selectedCells.addAll(selectedCellsBeforeRangeSelect);
        }
        else
        {
            selectedCells.clear();
        }




        GridColumn currentColumn = focusColumn;
        GridItem currentItem = focusItem;

        GridColumn endColumn = getColumn(newCell.x);
        GridItem endItem = getItem(newCell.y);

        Point newRange = getSelectionRange(currentItem,currentColumn,endItem,endColumn);

        currentColumn = getColumn(newRange.x);
        endColumn = getColumn(newRange.y);

        GridColumn startCol = currentColumn;

        if (indexOf(currentItem) > indexOf(endItem))
        {
            GridItem temp = currentItem;
            currentItem = endItem;
            endItem = temp;
        }

        boolean firstLoop = true;

        do
        {
            if (!firstLoop)
            {
                currentItem = getNextVisibleItem(currentItem);
            }

            firstLoop = false;

            boolean firstLoop2 = true;

            currentColumn = startCol;

            do
            {
                if (!firstLoop2)
                {
                    int index = displayOrderedColumns.indexOf(currentColumn) + 1;

                    if (index < displayOrderedColumns.size())
                    {
                        currentColumn = getVisibleColumn_DegradeRight(currentItem,(GridColumn)displayOrderedColumns.get(index));
                    }
                    else
                    {
                        currentColumn = null;
                    }

                    if (currentColumn!= null)
                        if (displayOrderedColumns.indexOf(currentColumn) > displayOrderedColumns.indexOf(endColumn))
                            currentColumn = null;
                }

                firstLoop2 = false;

                if (currentColumn != null)
                {
                    Point cell = new Point(indexOf(currentColumn),indexOf(currentItem));
                    addToCellSelection(cell);
                }
            } while (currentColumn != endColumn && currentColumn != null);
        } while (currentItem != endItem);
    }
    else if (ctrl)
    {
        boolean reverse = reverseDuplicateSelections;
        if (!selectedCells.containsAll(newCells))
            reverse = false;

        if (dragging)
        {
            selectedCells.clear();
            selectedCells.addAll(selectedCellsBeforeRangeSelect);
        }

        if (reverse)
        {
            selectedCells.removeAll(newCells);
        }
        else
        {
            for (int i = 0; i < newCells.size(); i++)
            {
                addToCellSelection((Point)newCells.get(i));
            }
        }
    }

    updateColumnSelection();

    Event e = new Event();
    if (dragging)
    {
        e.detail = SWT.DRAG;
        followupCellSelectionEventOwed = true;
    }

    Rectangle clientArea = getClientArea();
    redraw(clientArea.x,clientArea.y,clientArea.width,clientArea.height,false);

    return e;
}
 
Example 27
Project: JDK   File: Stylesheet.java View source code Vote up 5 votes
/**
 * This method returns a vector with variables/params and keys in the
 * order in which they are to be compiled for initialization. The order
 * is determined by analyzing the dependencies between them. The XSLT 1.0
 * spec does not allow a key to depend on a variable. However, for
 * compatibility with Xalan interpretive, that type of dependency is
 * allowed and, therefore, consider to determine the partial order.
 */
private Vector resolveDependencies(Vector input) {
    /* DEBUG CODE - INGORE
    for (int i = 0; i < input.size(); i++) {
        final TopLevelElement e = (TopLevelElement) input.elementAt(i);
        System.out.println("e = " + e + " depends on:");
        Vector dep = e.getDependencies();
        for (int j = 0; j < (dep != null ? dep.size() : 0); j++) {
            System.out.println("\t" + dep.elementAt(j));
        }
    }
    System.out.println("=================================");
    */

    Vector result = new Vector();
    while (input.size() > 0) {
        boolean changed = false;
        for (int i = 0; i < input.size(); ) {
            final TopLevelElement vde = (TopLevelElement) input.elementAt(i);
            final Vector dep = vde.getDependencies();
            if (dep == null || result.containsAll(dep)) {
                result.addElement(vde);
                input.remove(i);
                changed = true;
            }
            else {
                i++;
            }
        }

        // If nothing was changed in this pass then we have a circular ref
        if (!changed) {
            ErrorMsg err = new ErrorMsg(ErrorMsg.CIRCULAR_VARIABLE_ERR,
                                        input.toString(), this);
            getParser().reportError(Constants.ERROR, err);
            return(result);
        }
    }

    /* DEBUG CODE - INGORE
    System.out.println("=================================");
    for (int i = 0; i < result.size(); i++) {
        final TopLevelElement e = (TopLevelElement) result.elementAt(i);
        System.out.println("e = " + e);
    }
    */

    return result;
}