Java Code Examples for java.util.ArrayList.size()

The following are Jave code examples for showing how to use size() of the java.util.ArrayList class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: cniao5   File: PlatformPage.java   View Source Code Vote up 7 votes
protected ArrayList<Object> collectCells() {
    ArrayList<Object> cells = new ArrayList<Object>();

    Platform[] platforms = ShareSDK.getPlatformList();
    if (platforms == null) {
        platforms = new Platform[0];
    }
    HashMap<String, String> hides = getHiddenPlatforms();
    if (hides == null) {
        hides = new HashMap<String, String>();
    }
    for (Platform p : platforms) {
        if (!hides.containsKey(p.getName())) {
            cells.add(p);
        }
    }

    ArrayList<CustomerLogo> customers = getCustomerLogos();
    if (customers != null && customers.size() > 0) {
        cells.addAll(customers);
    }

    return cells;
}
 
Example 2
Project: letv   File: ac.java   View Source Code Vote up 6 votes
private static void a(Context context, JSONObject jSONObject, ArrayList<JSONArray> arrayList) {
    if (arrayList.size() <= 0) {
        b(context);
    }
    JSONArray jSONArray = new JSONArray();
    for (int i = 0; i < arrayList.size(); i++) {
        JSONArray jSONArray2 = (JSONArray) arrayList.get(i);
        for (int i2 = 0; i2 < jSONArray2.length(); i2++) {
            if (jSONArray2.optJSONObject(i2) != null) {
                jSONArray.put(jSONArray2.optJSONObject(i2));
            }
        }
    }
    try {
        jSONObject.put(z[6], jSONArray);
    } catch (JSONException e) {
    }
    a = jSONObject;
    a(context, z[11], jSONObject);
}
 
Example 3
Project: Moenagade   File: Element.java   View Source Code Vote up 5 votes
public boolean hasVariableWithNameInBlock(String value)
{
    ArrayList<VariableDefinition> vd = getVariablesInBlock();
    //System.out.println(vd.size());
    for (int j = 0; j < vd.size(); j++) {
        VariableDefinition get = vd.get(j);
        //System.out.println(get.name+ " vs: "+value);
        if(get.name.equals(value))
            return true;
    }
    return false;
}
 
Example 4
Project: StructPro   File: Village.java   View Source Code Vote up 5 votes
/**
 * Generate projection set combined from village that spawned in specific position
 * @param world Target world object
 * @param village Village structures
 * @param chunkX Chunk X coordinate
 * @param chunkZ Chunk Z coordinate
 * @param seed Combination seed
 * @return Array of spawned projections
 */
public static ArrayList<Projection> combine(final UWorld world, final ArrayList<Structure> village, final int chunkX, final int chunkZ, final long seed) {
    ArrayList<Projection> projections = new ArrayList<>();
    Random random = new Random(seed);
    String villageName = village.get(0).getFile().getParent();
    int side = (int) (1 + Math.sqrt(village.size()));
    for (int i = 0, maxSize = 0, offsetX = 0, offsetZ = 0; i < village.size(); ++i) {
        int posX = i % side;
        if (posX == 0) {
            offsetX = 0;
            offsetZ += maxSize;
            maxSize = 0;
        }
        Structure structure = village.get(i);
        int realX = chunkX * 16 + offsetX;
        int realZ = chunkZ * 16 + offsetZ;
        int curSize = Math.max(structure.getWidth(), structure.getLength());
        maxSize = Math.max(maxSize, curSize);
        offsetX += maxSize;
        if (!Limiter.isStructureLimitExceeded(world, structure)) {
            Projection projection = construct(world, realX, realZ, random.nextLong(), structure);
            if (projection != null) {
                projections.add(projection);
                Limiter.useStructure(world, structure);
            }
        }
    }
    new Report().post("VILLAGE", villageName).post("CHUNK", "[X=" + chunkX + ";Z=" + chunkZ + "]").post("TOTAL SPAWNED", String.valueOf(projections.size())).print();
    return projections;
}
 
Example 5
Project: automatic-variants   File: AV.java   View Source Code Vote up 5 votes
@Override
   public boolean needsPatching() {


//Need to check if packages have changed.
ArrayList<File> files = Ln.generateFileList(new File(AVFileVars.AVPackagesDir), false);
try {
    ArrayList<String> last = AVFileVars.getAVPackagesListing();
    if (files.size() != last.size()) {
	if (SPGlobal.logging()) {
	    SPGlobal.logMain(header, "Needs update because number of package files changed.");
	}
	return true;
    }

    for (File f : files) {
	String path = f.getPath();
	if (!last.contains(path)) {
	    if (SPGlobal.logging()) {
		SPGlobal.logMain(header, "Needs update because last package list didn't contain: " + path);
	    }
	    return true;
	}
    }

} catch (IOException ex) {
    SPGlobal.logException(ex);
    return true;
}
return false;
   }
 
Example 6
Project: FormatEditText   File: FormattedEditText.java   View Source Code Vote up 5 votes
private void sendBeforeTextChanged(CharSequence text, int start, int before, int after) {
    if (mWatchers != null) {
        final ArrayList<TextWatcher> list = mWatchers;
        final int size = list.size();
        for (int i = 0; i < size; i++) {
            list.get(i).beforeTextChanged(text, start, before, after);
        }
    }
}
 
Example 7
Project: monarch   File: PartitionRegionConfigValidator.java   View Source Code Vote up 5 votes
private void validatePartitionListeners(final PartitionRegionConfig prconf,
    final PartitionAttributes userPA) {

  ArrayList<String> prconfList = prconf.getPartitionListenerClassNames();

  if (userPA.getPartitionListeners() == null && userPA.getPartitionListeners().length == 0
      && prconfList != null) {
    throw new IllegalStateException(
        LocalizedStrings.PartitionRegionConfigValidator_INCOMPATIBLE_PARTITION_LISTENER
            .toLocalizedString(new Object[] {null, prconfList}));
  }
  if (userPA.getPartitionListeners() != null && prconfList != null) {
    ArrayList<String> userPRList = new ArrayList<String>();
    for (int i = 0; i < userPA.getPartitionListeners().length; i++) {
      userPRList.add(userPA.getPartitionListeners()[i].getClass().getName());
    }

    if (userPA.getPartitionListeners().length != prconfList.size()) {
      throw new IllegalStateException(
          LocalizedStrings.PartitionRegionConfigValidator_INCOMPATIBLE_PARTITION_LISTENER
              .toLocalizedString(new Object[] {userPRList, prconfList}));
    }

    for (String listener : prconfList) {
      if (!(userPRList.contains(listener))) {
        throw new IllegalStateException(
            LocalizedStrings.PartitionRegionConfigValidator_INCOMPATIBLE_PARTITION_LISTENER
                .toLocalizedString(new Object[] {userPRList, prconfList}));
      }
    }
  }
}
 
Example 8
Project: Rey-MusicPlayer   File: TracksSubGridViewFragment.java   View Source Code Vote up 5 votes
public boolean checkSongsEmpty(ArrayList<Song> songs, int pos) {
    if (songs.size() == 0) {
        mAlbums.remove(pos);
        mAdapter.updateData(mAlbums);
        Toast.makeText(mContext, R.string.no_songs_in_this_album, Toast.LENGTH_SHORT).show();
        return true;
    }
    return false;
}
 
Example 9
Project: ZentrelaCore   File: RLocation.java   View Source Code Vote up 5 votes
public static ArrayList<Location> findCastableLocs(Location origin, double radius, int count) {
    ArrayList<Location> locs = new ArrayList<Location>();
    if (radius < 0)
        radius = -radius;
    int cap = count * 2; // max number of spots to try to find valid locations at
    for (int k = 0; k < cap; k++) {
        double dx = RMath.randDouble(-radius, radius);
        double dz = RMath.randDouble(-radius, radius);
        origin.add(dx, 0, dz);
        for (int dy = 0; dy <= 3; dy++) {
            Location temp = origin.clone().add(0, dy, 0);
            if (checkLocation(temp)) {
                locs.add(temp);
                break;
            } else {
                if (checkLocation(temp.add(0, -dy * 2, 0))) {
                    locs.add(temp);
                    break;
                }
            }
        }
        if (locs.size() >= count)
            break;
    }
    if (locs.size() < count) {
        System.out.println("WARNING: findCastableLocs() at " + origin + " failed to find " + count + " locations in a radius of " + radius + ". " + locs.size() + " locations were found.");
    }
    return locs;
}
 
Example 10
Project: Appmatic-Android   File: MainActivity.java   View Source Code Vote up 5 votes
@Override
public void updateAllContent(ArrayList<AppContent> items) {
    if (currentNavigationViewMenu.size() > 0)
        currentNavigationViewMenu.clear();

    this.items = items;

    if (!InternetUtils.isInternetAvailable(this))
        Snackbar.make(findViewById(R.id.main_coordinator_layout), R.string.snackbar_cache_text,
                Snackbar.LENGTH_LONG).show();

    if (items == null) {
        handleInternetError(null);
        return;
    }

    for (int i = 0; i < items.size(); i++) {
        AppContent item = items.get(i);
        menuIdPosition.put(item.getContent_id(), i);
        if (AppmaticUtils.getIconRes(item.getIcon_id(), this) == -1)
            currentNavigationViewMenu.add(R.id.main_group_menu, item.getContent_id(), i, item.getName());
        else
            currentNavigationViewMenu.add(R.id.main_group_menu, item.getContent_id(), i,
                    item.getName()).setIcon(AppmaticUtils.getIconRes(item.getIcon_id(), this));
    }

    mainPresenter.getExtraItems();
}
 
Example 11
Project: OpenJSharp   File: Utility.java   View Source Code Vote up 5 votes
/**
 * @param  signature    Method signature
 * @param chopit Shorten class names ?
 * @return Array of argument types
 * @throws  ClassFormatException
 */
public static final String[] methodSignatureArgumentTypes(String signature,
                                                          boolean chopit)
  throws ClassFormatException
{
  ArrayList vec = new ArrayList();
  int       index;
  String[]  types;

  try { // Read all declarations between for `(' and `)'
    if(signature.charAt(0) != '(')
      throw new ClassFormatException("Invalid method signature: " + signature);

    index = 1; // current string position

    while(signature.charAt(index) != ')') {
      vec.add(signatureToString(signature.substring(index), chopit));
      index += consumed_chars; // update position
    }
  } catch(StringIndexOutOfBoundsException e) { // Should never occur
    throw new ClassFormatException("Invalid method signature: " + signature);
  }

  types = new String[vec.size()];
  vec.toArray(types);
  return types;
}
 
Example 12
Project: stynico   File: WxArticleAPIActivity.java   View Source Code Vote up 5 votes
public void onSuccess(API api, int action, Map<String, Object> result) {
    ArrayList<HashMap<String, Object>> res = forceCast(result.get("result"));
    if (null != res && res.size() > 0) {
        categoryList.clear();
        categoryList.addAll(res);
        categoryAdapter.notifyDataSetChanged();
    }
}
 
Example 13
Project: brModelo   File: Sintaxe.java   View Source Code Vote up 5 votes
public String AutoComplete(ArrayList<String> comm, int nv) {
    if (nv > comm.size() - 1) {
        return "";
    }
    String tmp = comm.get(nv);
    String res = getBestCMD(tmp);
    if (res.isEmpty()) {
        return tmp;
    }
    if (isCMDTipoVariavel()) {
        res = tmp;
    }

    nv++;
    if (nv == comm.size()) {
        if (Proximos.isEmpty()) {
            return res;
        }
        return res + " ";
    }

    int tmpnv = nv;
    Sintaxe prx = null;
    for (Sintaxe sx : Proximos) {
        int idx = sx.getNivelDeValidade(comm, nv);
        if (idx > tmpnv) {
            tmpnv = idx;
            prx = sx;
        }
    }
    if (prx == null) {
        return res + " " + comm.get(nv);
    }
    return res + " " + prx.AutoComplete(comm, nv);
}
 
Example 14
Project: jdk8u-jdk   File: ConcurrentSkipListMap.java   View Source Code Vote up 4 votes
/**
 * Reconstitutes this map from a stream (that is, deserializes it).
 * @param s the stream
 * @throws ClassNotFoundException if the class of a serialized object
 *         could not be found
 * @throws java.io.IOException if an I/O error occurs
 */
@SuppressWarnings("unchecked")
private void readObject(final java.io.ObjectInputStream s)
    throws java.io.IOException, ClassNotFoundException {
    // Read in the Comparator and any hidden stuff
    s.defaultReadObject();
    // Reset transients
    initialize();

    /*
     * This is nearly identical to buildFromSorted, but is
     * distinct because readObject calls can't be nicely adapted
     * as the kind of iterator needed by buildFromSorted. (They
     * can be, but doing so requires type cheats and/or creation
     * of adaptor classes.) It is simpler to just adapt the code.
     */

    HeadIndex<K,V> h = head;
    Node<K,V> basepred = h.node;
    ArrayList<Index<K,V>> preds = new ArrayList<Index<K,V>>();
    for (int i = 0; i <= h.level; ++i)
        preds.add(null);
    Index<K,V> q = h;
    for (int i = h.level; i > 0; --i) {
        preds.set(i, q);
        q = q.down;
    }

    for (;;) {
        Object k = s.readObject();
        if (k == null)
            break;
        Object v = s.readObject();
        if (v == null)
            throw new NullPointerException();
        K key = (K) k;
        V val = (V) v;
        int rnd = ThreadLocalRandom.current().nextInt();
        int j = 0;
        if ((rnd & 0x80000001) == 0) {
            do {
                ++j;
            } while (((rnd >>>= 1) & 1) != 0);
            if (j > h.level) j = h.level + 1;
        }
        Node<K,V> z = new Node<K,V>(key, val, null);
        basepred.next = z;
        basepred = z;
        if (j > 0) {
            Index<K,V> idx = null;
            for (int i = 1; i <= j; ++i) {
                idx = new Index<K,V>(z, idx, null);
                if (i > h.level)
                    h = new HeadIndex<K,V>(h.node, h, idx, i);

                if (i < preds.size()) {
                    preds.get(i).right = idx;
                    preds.set(i, idx);
                } else
                    preds.add(idx);
            }
        }
    }
    head = h;
}
 
Example 15
Project: mazes_and_minotaurs   File: Priest.java   View Source Code Vote up 4 votes
public void doLevelUp(Score score) {
    if (getLevel() < getEffectiveLevel()){

        Score[] choices = {Score.SKILL, Score.WILL, Score.MIGHT, Score.WITS};
        ArrayList<Score> possibleScores = new ArrayList<>();
        for (Score selectScore: choices) {
            if(getCharacter().canAddToScore(selectScore)) {
                possibleScores.add(selectScore);
            }
        }

        Score selectedScore;
        if (possibleScores.contains(score)) {
            selectedScore = score;
        } else {
            selectedScore = possibleScores.get(rollDice.roll(possibleScores.size()) - 1);
        }

        if (possibleScores.size() > 0) {
            while (!getCharacter().canAddToScore(selectedScore)) {
                selectedScore = possibleScores.get((possibleScores.indexOf(selectedScore) + 1) % possibleScores.size());
            }
        }

        // Contains information about changed scores
        HashMap<Score, Integer> levelData = new HashMap<>();

        if (getCharacter().canAddToScore(Score.LUCK)) {
            AttributeScore luck = getCharacter().getScore(Score.LUCK);
            levelData.put(Score.LUCK, luck.getScore());
            luck.setScore(luck.getScore() + 1);
        } else {
            levelData.put(Score.LUCK, 20);
        }

        AttributeScore selectedAttrScore = getCharacter().getScore(selectedScore);

        levelData.put(selectedScore, selectedAttrScore.getScore());
        getScoreLevelChoice().add(levelData);

        selectedAttrScore.setScore(selectedAttrScore.getScore() + 2);
        setAddedHits(getAddedHits() + 2);

        setLevel(getLevel() + 1);
        getCharacter().validateScores();
    }
}
 
Example 16
Project: RiskBots   File: BotStarter.java   View Source Code Vote up 4 votes
@Override
/**
 * This method is called for at the second part of each round. This example attacks if a region has
 * more than 6 armies on it, and transfers if it has less than 6 and a neighboring owned region.
 * @return The list of PlaceArmiesMoves for one round
 */
public ArrayList<AttackTransferMove> getAttackTransferMoves(Bot bot, BotState state, Long timeOut) 
{
	ArrayList<AttackTransferMove> attackTransferMoves = new ArrayList<AttackTransferMove>();
	String myName = state.getMyPlayerName();
	int armies = 5;
	
	for(Region fromRegion : state.getVisibleMap().getRegions())
	{
		if(fromRegion.ownedByPlayer(myName)) //do an attack
		{
			ArrayList<Region> possibleToRegions = new ArrayList<Region>();
			possibleToRegions.addAll(fromRegion.getNeighbors());
			
			while(!possibleToRegions.isEmpty())
			{
				double rand = Math.random();
				int r = (int) (rand*possibleToRegions.size());
				Region toRegion = possibleToRegions.get(r);
				
				if(!toRegion.getPlayerName().equals(myName) && fromRegion.getArmies() > 3) //do an attack
				{
					attackTransferMoves.add(new AttackTransferMove(myName, fromRegion, toRegion, fromRegion.getArmies()/2));
					break;
				}
				else if(toRegion.getPlayerName().equals(myName) && isBorder(toRegion, myName) && fromRegion.getArmies() > 1) //do a transfer
				{
					if(!isBorder(fromRegion, myName)){
					attackTransferMoves.add(new AttackTransferMove(myName, fromRegion, toRegion, fromRegion.getArmies()-1));
				}
					break;
				 
				}
				else
					possibleToRegions.remove(toRegion);
			}
		}
	}
	
	return attackTransferMoves;
}
 
Example 17
Project: Customerly-Android-SDK   File: IAct_Chat.java   View Source Code Vote up 4 votes
@Override
public void onNewSocketMessages(@NonNull ArrayList<IE_Message> messages) {
    final ArrayList<IE_Message> new_messages = new ArrayList<>(this._ChatList);
    IE_Message otherConversationMessage = null;
    //noinspection Convert2streamapi
    for(IE_Message newMsg : messages) {
        if(newMsg.conversation_id == this._ConversationID) {       //Filter by conversation_id
            if(! new_messages.contains(newMsg)) {           //Avoid duplicates;
                new_messages.add(newMsg);
            }
        } else {
            if(otherConversationMessage == null || otherConversationMessage.conversation_message_id < newMsg.conversation_message_id) {
                otherConversationMessage = newMsg;
            }
        }
    }

    if(otherConversationMessage != null) {
        try {
            PW_AlertMessage.show(this, otherConversationMessage);
        } catch (WindowManager.BadTokenException ignored) { }
    }

    Collections.sort(new_messages, (m1, m2) -> (int) (m2.conversation_message_id - m1.conversation_message_id));//Sorting by conversation_message_id DESC

    IU_NullSafe.post(this._ListRecyclerView, () -> {
        boolean scrollToBottom = this._LinearLayoutManager != null && this._LinearLayoutManager.findFirstCompletelyVisibleItemPosition() == 0;
        this._ChatList = new_messages;
        this._Adapter.notifyDataSetChanged();
        if (scrollToBottom) {
            this._LinearLayoutManager.scrollToPosition(0);
        }
    });

    if(new_messages.size() != 0) {
        IE_Message last = new_messages.get(0);
        if (last.isNotSeen()) {
            this.sendSeen(last.conversation_message_id);
        }
    }
}
 
Example 18
Project: SkyWarsReloaded   File: JoinMenu.java   View Source Code Vote up 4 votes
public void updateJoinMenu(final GamePlayer gamePlayer) {
if (!SkyWarsReloaded.getIC().has(gamePlayer.getP()) || gamePlayer.inGame() || !SkyWarsReloaded.getIC().getMenu(gamePlayer.getP()).getName().equalsIgnoreCase(joinName)) {
	return;
} else {
       ArrayList<Game> games = SkyWarsReloaded.getGC().getGames();
       
       for (int iii = 0; iii < games.size(); iii++) {
           if (iii >= menuSize) {
               break;
           }

           Game game = games.get(iii);
           	            
           List<String> loreList = Lists.newLinkedList();
           if (game.getState() != GameState.PREGAME) {
            loreList.add((new Messaging.MessageFormatter().format("signJoinSigns.inprogress").toUpperCase()));
           }
           loreList.add(ChatColor.RED + "" + ChatColor.BOLD + game.getMapName().toUpperCase());
              loreList.add((new Messaging.MessageFormatter().format("menu.spectate-game-header") + "  " + game.getPlayers().size() + "/" + game.getNumberOfSpawns()));
           for (GamePlayer gPlayer: game.getPlayers()) {
           	if (gPlayer.getP() != null) {
            	loreList.add(ChatColor.WHITE + gPlayer.getP().getName());
           	}
           }
           
           double xy = ((double) (game.getPlayers().size() / game.getNumberOfSpawns()));
           
           Material gameIcon = Material.REDSTONE_BLOCK;
           String gameNumber = String.valueOf(game.getGameNumber());
           if (game.getState() == GameState.PREGAME) {
           	gameIcon =  Material.DIAMOND_HELMET;
   	    	if (xy < 0.75) {
   	    		gameIcon = Material.GOLD_HELMET;
   	    	} 
   	    	if (xy < 0.50) {
   	    		gameIcon =  Material.IRON_HELMET;
   	    	} 
   	    	if (xy < 0.25) {
   	    		gameIcon =  Material.LEATHER_HELMET;
   	    	} 
           }  
           
           if (gamePlayer.getP() != null) {
            SkyWarsReloaded.getIC().setOption(
                    gamePlayer.getP(),
                    iii,
                    new ItemStack(gameIcon, 1),
                    gameNumber,
                    loreList.toArray(new String[loreList.size()]));
           }
          }
       
       if (gamePlayer.getP() != null && !gamePlayer.inGame()) {
        SkyWarsReloaded.getIC().update(gamePlayer.getP());
       }
       
       final GamePlayer player = gamePlayer;

       SkyWarsReloaded.get().getServer().getScheduler().scheduleSyncDelayedTask(SkyWarsReloaded.get(), new Runnable() {
		@Override
		public void run() {
			updateJoinMenu(player);	
		}
       }, 40); 
}
  }
 
Example 19
Project: atlas   File: ActivityTaskMgr.java   View Source Code Vote up 4 votes
public void updateBundleActivityResource(String bundleName){
    for(int x=0; x<activityList.size(); x++){
        WeakReference<Activity> ref = activityList.get(x);
        if(ref!=null && ref.get()!=null && !ref.get().isFinishing()){
            Activity activity =  ref.get();
            try {
                if(Build.VERSION.SDK_INT>=17 && activity.getResources()!=RuntimeVariables.delegateResources) {
                    Field mResourcesField = Activity.class.getSuperclass().getDeclaredField("mResources");
                    mResourcesField.setAccessible(true);
                    mResourcesField.set(activity, RuntimeVariables.delegateResources);
                }
                Field mThemeField = Activity.class.getSuperclass().getDeclaredField("mTheme");
                mThemeField.setAccessible(true);
                Object mTheme = mThemeField.get(activity);
                Field mReferenceResource = mTheme.getClass().getDeclaredField("this$0");
                mReferenceResource.setAccessible(true);
                if(mReferenceResource.get(mTheme) != RuntimeVariables.delegateResources){
                    mThemeField.set(activity, null);
                }

                Class TintContextWrapper = Class.forName("android.support.v7.widget.TintContextWrapper");
                Field tintWrapperField = TintContextWrapper.getDeclaredField("sCache");
                tintWrapperField.setAccessible(true);
                ArrayList<WeakReference<Object>> sCache = (ArrayList<WeakReference<Object>>)tintWrapperField.get(TintContextWrapper);

                if(sCache!=null){
                    for(int n=0; n<sCache.size();n++){
                        final WeakReference<Object> wrappRef = sCache.get(n);
                        final Object wrapper = wrappRef != null ? wrappRef.get() : null;
                        if (wrapper != null && ((ContextWrapper)wrapper).getBaseContext() == activity) {
                            Field mTintResourcesField = TintContextWrapper.getDeclaredField("mResources");
                            mTintResourcesField.setAccessible(true);
                            mTintResourcesField.set(wrapper,RuntimeVariables.delegateResources);
                            break;
                        }
                    }
                }
            } catch (Throwable e) {
                //e.printStackTrace();
            }

        }
    }
}
 
Example 20
Project: jdk8u-jdk   File: IPPPrintService.java   View Source Code Vote up 4 votes
private void initAttributes() {
    if (!init) {
        // init customMediaSizeNames
        customMediaSizeNames = new CustomMediaSizeName[0];

        if ((urlConnection = getIPPConnection(myURL)) == null) {
            mediaSizeNames = new MediaSizeName[0];
            mediaTrays = new MediaTray[0];
            debug_println(debugPrefix+"initAttributes, NULL urlConnection ");
            init = true;
            return;
        }

        // get all supported attributes through IPP
        opGetAttributes();

        if (isCupsPrinter) {
            // note, it is possible to query media in CUPS using IPP
            // right now we always get it from PPD.
            // maybe use "&& (usePPD)" later?
            // Another reason why we use PPD is because
            // IPP currently does not support it but PPD does.

            try {
                cps = new CUPSPrinter(printer);
                mediaSizeNames = cps.getMediaSizeNames();
                mediaTrays = cps.getMediaTrays();
                customMediaSizeNames = cps.getCustomMediaSizeNames();
                defaultMediaIndex = cps.getDefaultMediaIndex();
                urlConnection.disconnect();
                init = true;
                return;
            } catch (Exception e) {
                IPPPrintService.debug_println(debugPrefix+
                                   "initAttributes, error creating CUPSPrinter e="+e);
            }
        }

        // use IPP to get all media,
        Media[] allMedia = (Media[])getSupportedMedia();
        ArrayList sizeList = new ArrayList();
        ArrayList trayList = new ArrayList();
        for (int i=0; i<allMedia.length; i++) {
            if (allMedia[i] instanceof MediaSizeName) {
                sizeList.add(allMedia[i]);
            } else if (allMedia[i] instanceof MediaTray) {
                trayList.add(allMedia[i]);
            }
        }

        if (sizeList != null) {
            mediaSizeNames = new MediaSizeName[sizeList.size()];
            mediaSizeNames = (MediaSizeName[])sizeList.toArray(
                                                   mediaSizeNames);
        }
        if (trayList != null) {
            mediaTrays = new MediaTray[trayList.size()];
            mediaTrays = (MediaTray[])trayList.toArray(
                                                       mediaTrays);
        }
        urlConnection.disconnect();

        init = true;
    }
}