Example usage for java.util HashSet size

List of usage examples for java.util HashSet size

Introduction

In this page you can find the example usage for java.util HashSet size.

Prototype

public int size() 

Source Link

Document

Returns the number of elements in this set (its cardinality).

Usage

From source file:org.pentaho.reporting.libraries.formula.function.DefaultFunctionRegistry.java

public void initialize(final Configuration configuration) {
    final Iterator functionKeys = configuration.findPropertyKeys(FUNCTIONS_PREFIX);
    final HashSet<FunctionCategory> categories = new HashSet<FunctionCategory>();

    while (functionKeys.hasNext()) {
        final String classKey = (String) functionKeys.next();
        if (classKey.endsWith(".class") == false) {
            continue;
        }/*w  ww . j  a va  2  s  .c o  m*/

        final String className = configuration.getConfigProperty(classKey);
        if (className.length() == 0) {
            continue;
        }
        final Object fn = ObjectUtilities.loadAndInstantiate(className, DefaultFunctionRegistry.class,
                Function.class);
        if (fn instanceof Function == false) {
            continue;
        }

        final Function function = (Function) fn;

        final int endIndex = classKey.length() - 6; // 6 = ".class".length();
        final String descrKey = classKey.substring(0, endIndex) + ".description";
        final String descrClassName = configuration.getConfigProperty(descrKey);
        final Object descr = ObjectUtilities.loadAndInstantiate(descrClassName, DefaultFunctionRegistry.class,
                FunctionDescription.class);

        final FunctionDescription description;
        if (descr instanceof FunctionDescription == false) {
            description = new DefaultFunctionDescription(function.getCanonicalName());
        } else {
            description = (FunctionDescription) descr;
        }

        final FunctionCategory cat = description.getCategory();
        categoryFunctions.add(cat, function.getCanonicalName());
        functionMetaData.put(function.getCanonicalName(), description);
        functions.put(function.getCanonicalName(), className);
        categories.add(cat);
    }

    this.categories = categories.toArray(new FunctionCategory[categories.size()]);
}

From source file:org.commoncrawl.mapred.ec2.postprocess.crawldb.CrawlDBMergingReducer.java

/** 
 * given html content (json object), extract out of domain hrefs and cache them 
 * and ... update stats /*from   ww w  . j  a  v a 2 s  . c o m*/
 * @param crawlStats
 * @param incomingJSONObject
 * @param extHRefs
 * @param fpSource
 * @param reporter
 */
static void updateLinkStatsFromHTMLContent(JsonObject crawlStats, JsonObject incomingJSONObject,
        HashSet<String> extHRefs, URLFPV2 fpSource, Reporter reporter) {
    JsonArray links = incomingJSONObject.getAsJsonArray("links");

    if (links == null) {
        reporter.incrCounter(Counters.NULL_LINKS_ARRAY, 1);
    } else {

        // clear our snapshot of externally referenced urls 
        // we only want to capture this information from 
        // the links extracted via the latest content
        if (extHRefs != null)
            extHRefs.clear();

        int intraDomainLinkCount = 0;
        int intraRootLinkCount = 0;
        int interDomainLinkCount = 0;

        for (JsonElement link : links) {
            JsonObject linkObj = link.getAsJsonObject();
            if (linkObj != null && linkObj.has("href")) {
                String href = linkObj.get("href").getAsString();
                GoogleURL urlObject = new GoogleURL(href);
                if (urlObject.isValid()) {
                    URLFPV2 linkFP = URLUtils.getURLFPV2FromURLObject(urlObject);
                    if (linkFP != null) {
                        if (linkFP.getRootDomainHash() == fpSource.getRootDomainHash()) {
                            if (linkFP.getDomainHash() == fpSource.getDomainHash()) {
                                intraDomainLinkCount++;
                            } else {
                                intraRootLinkCount++;
                            }
                        } else {
                            interDomainLinkCount++;
                            // track domains we link to
                            if (extHRefs != null) {
                                if (extHRefs.size() <= MAX_EXTERNALLY_REFERENCED_URLS) {
                                    extHRefs.add(urlObject.getCanonicalURL());
                                }
                            }
                        }
                    }
                }
            }
        }
        // update counts in crawl stats data structure ... 
        crawlStats.addProperty(CRAWLDETAIL_INTRADOMAIN_LINKS, intraDomainLinkCount);
        crawlStats.addProperty(CRAWLDETAIL_INTRAROOT_LINKS, intraRootLinkCount);
        crawlStats.addProperty(CRAWLDETAIL_INTERDOMAIN_LINKS, interDomainLinkCount);

        if (interDomainLinkCount <= 100) {
            reporter.incrCounter(Counters.INTERDOMAIN_LINKS_LTEQ_100, 1);
        } else if (interDomainLinkCount <= 1000) {
            reporter.incrCounter(Counters.INTERDOMAIN_LINKS_LTEQ_1000, 1);
        } else {
            reporter.incrCounter(Counters.INTERDOMAIN_LINKS_GT_1000, 1);
        }
    }
}

From source file:fastcall.FastCallSNP.java

private void updateTaxaBamPathMap(File[] bams) {
    String bamDirS = bams[0].getParent();
    String[] existingBam = new String[bams.length];
    for (int i = 0; i < bams.length; i++)
        existingBam[i] = bams[i].getName();
    Arrays.sort(existingBam);/*from  w  w w  .j  av a  2s .  co m*/
    HashSet<String> existingTaxaSet = new HashSet();
    HashMap<String, String[]> updatedTaxaBamMap = new HashMap();
    int cnt = 0;
    ArrayList<String> pathList = new ArrayList();
    for (int i = 0; i < taxaNames.length; i++) {
        String[] bamNames = taxaBamPathMap.get(taxaNames[i]);
        ArrayList<String> bamPathList = new ArrayList();
        for (int j = 0; j < bamNames.length; j++) {
            int index = Arrays.binarySearch(existingBam, bamNames[j]);
            if (index < 0)
                continue;
            String path = new File(bamDirS, bamNames[j]).getAbsolutePath();
            bamPathList.add(path);
            pathList.add(path);
            existingTaxaSet.add(taxaNames[i]);
        }
        if (bamPathList.isEmpty())
            continue;
        bamNames = bamPathList.toArray(new String[bamPathList.size()]);
        Arrays.sort(bamNames);
        updatedTaxaBamMap.put(taxaNames[i], bamNames);
        cnt += bamNames.length;
    }
    String[] updatedTaxaNames = existingTaxaSet.toArray(new String[existingTaxaSet.size()]);
    Arrays.sort(updatedTaxaNames);
    taxaNames = updatedTaxaNames;
    taxaBamPathMap = updatedTaxaBamMap;
    this.bamPaths = pathList.toArray(new String[pathList.size()]);
    Arrays.sort(bamPaths);
    System.out.println("Actual taxa number:\t" + String.valueOf(taxaNames.length));
    System.out.println("Actual bam file number:\t" + String.valueOf(cnt));
    System.out.println();
}

From source file:org.apache.hadoop.util.SysInfoLinux.java

/**
 * Read /proc/cpuinfo, parse and calculate CPU information.
 *//* w ww  .  j a va2  s.  co m*/
private void readProcCpuInfoFile() {
    // This directory needs to be read only once
    if (readCpuInfoFile) {
        return;
    }
    HashSet<String> coreIdSet = new HashSet<>();
    // Read "/proc/cpuinfo" file
    BufferedReader in;
    InputStreamReader fReader;
    try {
        fReader = new InputStreamReader(new FileInputStream(procfsCpuFile), Charset.forName("UTF-8"));
        in = new BufferedReader(fReader);
    } catch (FileNotFoundException f) {
        // shouldn't happen....
        LOG.warn("Couldn't read " + procfsCpuFile + "; can't determine cpu info");
        return;
    }
    Matcher mat;
    try {
        numProcessors = 0;
        numCores = 1;
        String currentPhysicalId = "";
        String str = in.readLine();
        while (str != null) {
            mat = PROCESSOR_FORMAT.matcher(str);
            if (mat.find()) {
                numProcessors++;
            }
            mat = FREQUENCY_FORMAT.matcher(str);
            if (mat.find()) {
                cpuFrequency = (long) (Double.parseDouble(mat.group(1)) * 1000); // kHz
            }
            mat = PHYSICAL_ID_FORMAT.matcher(str);
            if (mat.find()) {
                currentPhysicalId = str;
            }
            mat = CORE_ID_FORMAT.matcher(str);
            if (mat.find()) {
                coreIdSet.add(currentPhysicalId + " " + str);
                numCores = coreIdSet.size();
            }
            str = in.readLine();
        }
    } catch (IOException io) {
        LOG.warn("Error reading the stream " + io);
    } finally {
        // Close the streams
        try {
            fReader.close();
            try {
                in.close();
            } catch (IOException i) {
                LOG.warn("Error closing the stream " + in);
            }
        } catch (IOException i) {
            LOG.warn("Error closing the stream " + fReader);
        }
    }
    readCpuInfoFile = true;
}

From source file:org.apache.bookkeeper.client.RackawareEnsemblePlacementPolicyImpl.java

@Override
public boolean isEnsembleAdheringToPlacementPolicy(List<BookieSocketAddress> ensembleList, int writeQuorumSize,
        int ackQuorumSize) {
    int ensembleSize = ensembleList.size();
    int minNumRacksPerWriteQuorumForThisEnsemble = Math.min(writeQuorumSize, minNumRacksPerWriteQuorum);
    HashSet<String> racksInQuorum = new HashSet<String>();
    BookieSocketAddress bookie;//from ww  w.j av  a2  s  . com
    for (int i = 0; i < ensembleList.size(); i++) {
        racksInQuorum.clear();
        for (int j = 0; j < writeQuorumSize; j++) {
            bookie = ensembleList.get((i + j) % ensembleSize);
            try {
                racksInQuorum.add(knownBookies.get(bookie).getNetworkLocation());
            } catch (Exception e) {
                /*
                 * any issue/exception in analyzing whether ensemble is
                 * strictly adhering to placement policy should be
                 * swallowed.
                 */
                LOG.warn("Received exception while trying to get network location of bookie: {}", bookie, e);
            }
        }
        if ((racksInQuorum.size() < minNumRacksPerWriteQuorumForThisEnsemble)
                || (enforceMinNumRacksPerWriteQuorum && racksInQuorum.contains(getDefaultRack()))) {
            return false;
        }
    }
    return true;
}

From source file:de.tarent.maven.plugins.pkg.AbstractPackagingMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {

    // We will merge all targetConfigurations with their parents,
    // so tat all configurations are ready to be used from this point on

    Utils.mergeAllConfigurations(targetConfigurations);

    // For some tasks it is practical to have the TargetConfiguration
    // instances as a
    // map. This transformation step also serves as check for double
    // entries.//w w  w  . j av a  2s.  c  o m
    Map<String, TargetConfiguration> targetConfigurationMap = Utils.toMap(targetConfigurations);

    // Container for collecting target configurations that have been built.
    // This
    // is used to make sure that TCs are not build repeatedly when the given
    // target
    // configuration have a dependency to a common target configuration.
    HashSet<String> finishedTargets = new HashSet<String>();

    checkIfPackagesWillOverwrite();

    for (String t : getTargets()) {
        // A single target (and all its dependent target configurations are
        // supposed to use the same
        // distro value).
        String d = (distro != null) ? distro : Utils.getDefaultDistro(t, targetConfigurations, getLog());

        // Retrieve all target configurations that need to be build for /t/
        List<TargetConfiguration> buildChain = Utils.createBuildChain(t, d, targetConfigurations);

        for (TargetConfiguration tc : buildChain) {
            if (!finishedTargets.contains(tc.getTarget()) && tc.isReady()) {
                WorkspaceSession ws = new WorkspaceSession();
                ws.setMojo(this); // its us
                ws.setTargetConfigurationMap(targetConfigurationMap);
                ws.setTargetConfiguration(tc);

                // Populates session with PackageMap, Helper and resolved
                // relations
                prepareWorkspaceSession(ws, d);

                executeTargetConfiguration(ws);

                // Mark as done.
                finishedTargets.add(tc.getTarget());
            }

        }
    }
    getLog().info("pkg-maven-plugin goal succesfully executed for " + finishedTargets.size() + " target(s).");
    cleanUp();
}

From source file:com.compomics.util.experiment.identification.psm_scoring.psm_scores.HyperScore.java

/**
 * Returns the hyperscore./*  w  w  w  . ja  v a  2  s .c  o  m*/
 *
 * @param peptide the peptide of interest
 * @param spectrum the spectrum of interest
 * @param annotationSettings the general spectrum annotation settings
 * @param specificAnnotationSettings the annotation settings specific to
 * this PSM
 * @param ionMatches the ion matches obtained from spectrum annotation
 *
 * @return the score of the match
 */
public double getScore(Peptide peptide, MSnSpectrum spectrum, AnnotationSettings annotationSettings,
        SpecificAnnotationSettings specificAnnotationSettings, ArrayList<IonMatch> ionMatches) {

    boolean peakMatched = false;
    Double coveredIntensity = 0.0;
    HashSet<Double> coveredMz = new HashSet<Double>(2);
    for (IonMatch ionMatch : ionMatches) {
        Ion ion = ionMatch.ion;
        Peak peak = ionMatch.peak;
        if (!coveredMz.contains(peak.mz)) {
            coveredIntensity += peak.intensity;
            coveredMz.add(peak.mz);
        }
        if (ion.getType() == Ion.IonType.PEPTIDE_FRAGMENT_ION) {
            PeptideFragmentIon peptideFragmentIon = (PeptideFragmentIon) ion;
            if (peptideFragmentIon.hasNeutralLosses() || peptideFragmentIon.getNumber() < 2) {
            } else {
                peakMatched = true;
            }
        }
    }
    if (!peakMatched) {
        return 0.0;
    }

    SpectrumIndex spectrumIndex = new SpectrumIndex();
    spectrumIndex = (SpectrumIndex) spectrum.getUrParam(spectrumIndex);
    if (spectrumIndex == null) {
        // Create new index
        spectrumIndex = new SpectrumIndex(spectrum.getPeakMap(),
                spectrum.getIntensityLimit(annotationSettings.getAnnotationIntensityLimit()),
                annotationSettings.getFragmentIonAccuracy(), annotationSettings.isFragmentIonPpm());
        spectrum.addUrParam(spectrumIndex);
    }

    Double totalIntensity = spectrumIndex.getTotalIntensity() - coveredIntensity;

    double xCorr = 0;
    HashSet<Integer> ionsForward = new HashSet<Integer>(1);
    HashSet<Integer> ionsRewind = new HashSet<Integer>(1);
    HashSet<Double> accountedFor = new HashSet<Double>(ionMatches.size());
    for (IonMatch ionMatch : ionMatches) {
        Peak peakI = ionMatch.peak;
        Double mz = peakI.mz;
        Ion ion = ionMatch.ion;
        if (ion.getType() == Ion.IonType.PEPTIDE_FRAGMENT_ION && !ion.hasNeutralLosses()
                && !accountedFor.contains(mz)) {
            PeptideFragmentIon peptideFragmentIon = (PeptideFragmentIon) ion;
            int number = peptideFragmentIon.getNumber();
            if (number > 1) {
                accountedFor.add(mz);
                Double x0I = peakI.intensity / totalIntensity;
                xCorr += x0I;
                if (ion.getType() == Ion.IonType.PEPTIDE_FRAGMENT_ION && !ion.hasNeutralLosses()) {
                    if (ion.getSubType() == PeptideFragmentIon.X_ION
                            || ion.getSubType() == PeptideFragmentIon.Y_ION
                            || ion.getSubType() == PeptideFragmentIon.Z_ION) {
                        ionsForward.add(number);
                    } else if (ion.getSubType() == PeptideFragmentIon.A_ION
                            || ion.getSubType() == PeptideFragmentIon.B_ION
                            || ion.getSubType() == PeptideFragmentIon.C_ION) {
                        ionsRewind.add(number);
                    }
                }
            }
        }
    }
    int nForward = ionsForward.size() / (Math.max(specificAnnotationSettings.getPrecursorCharge() - 1, 1));
    int nRewind = ionsRewind.size() / (Math.max(specificAnnotationSettings.getPrecursorCharge() - 1, 1));
    nForward = nForward > 20 ? 20 : nForward;
    nRewind = nRewind > 20 ? 20 : nRewind;
    long forwardFactorial = BasicMathFunctions.factorial(nForward);
    long rewindFactorial = BasicMathFunctions.factorial(nRewind);
    return xCorr * forwardFactorial * rewindFactorial;
}

From source file:org.archive.modules.CrawlURI.java

/** Make the given key non-'heritable', meaning its value will 
 * not be added to descendant CrawlURIs. Only meaningful if
 * key was previously made heritable.  /*from   w  w  w  . j a va2  s .  c  om*/
 * 
 * @param key to make non-heritable
 */
public void makeNonHeritable(String key) {
    @SuppressWarnings("unchecked")
    HashSet<String> heritableKeys = (HashSet<String>) data.get(A_HERITABLE_KEYS);
    if (heritableKeys == null) {
        return;
    }
    heritableKeys.remove(key);
    if (heritableKeys.size() == 1) {
        // only remaining heritable key is itself; disable completely
        data.remove(A_HERITABLE_KEYS);
    }
}

From source file:free.yhc.feeder.ChannelListFragment.java

@Override
public void onResume() {
    super.onResume();
    //logI("==> ChannelListActivity : onResume");
    // NOTE/*w w  w .  j a va  2  s .  com*/
    // Case to think about
    // - new update task is registered between 'registerManagerEventListener' and 'getUpdateState'
    // - then, this task will be binded twice.
    // => This leads to over head operation (ex. refreshing list two times continuously etc.)
    //    But, this doesn't issue logical error. So, I can get along with this case.
    //
    // If 'registerManagerEventListener' is below 'getUpdateState',
    //   we may miss binding some updating task!
    mRtt.registerRegisterEventListener(this, new RTTaskRegisterListener());

    HashSet<Long> updatedCids = new HashSet<Long>();
    for (long cid : mDbWatcher.getUpdatedChannels())
        updatedCids.add(cid);

    HashSet<Long> myUpdatedCids = new HashSet<Long>();
    // Check channel state and bind it.
    // Why here? Not 'onStart'.
    // See comments in 'onPause()'
    try {
        mDbp.getDelayedChannelUpdate();
        Cursor c = mDbp.queryChannel(mCatId, ColumnChannel.ID);
        if (c.moveToFirst()) {
            do {
                long cid = c.getLong(0);
                if (updatedCids.contains(cid))
                    myUpdatedCids.add(cid);

                if (RTTask.TaskState.IDLE != mRtt.getState(cid, RTTask.Action.UPDATE))
                    mRtt.bind(cid, RTTask.Action.UPDATE, this, new UpdateBGTaskListener(cid));
                long[] ids = mRtt.getItemsDownloading(cid);
                for (long id : ids)
                    mRtt.bind(id, RTTask.Action.DOWNLOAD, this, new DownloadBGTaskListener(cid));
            } while (c.moveToNext());
        }
        c.close();
    } finally {
        mDbp.putDelayedChannelUpdate();
    }

    // NOTE
    // Channel may be added or deleted.
    // And channel operation is only allowed on current selected list
    //   according to use case.
    if (mDbWatcher.isChannelTableUpdated() && myUpdatedCids.size() > 0) {
        refreshListAsync();
    } else
        refreshListItem(Utils.convertArrayLongTolong(myUpdatedCids.toArray(new Long[0])));

    // We don't need to worry about item table change.
    // Because, if item is newly inserted, that means some of channel is updated.
    // And that channel will be updated according to DB changes.

    mDbWatcher.unregister();
    mDbWatcher.reset();
}

From source file:net.countercraft.movecraft.async.rotation.RotationTask.java

@Override
public void excecute() {

    int waterLine = 0;

    int[][][] hb = getCraft().getHitBox();
    if (hb == null)
        return;//  w w  w.  j ava 2s . c o  m

    // Determine craft borders
    int minY = 65535;
    int maxY = -65535;
    for (int[][] i1 : hb) {
        for (int[] i2 : i1) {
            if (i2 != null) {
                if (i2[0] < minY) {
                    minY = i2[0];
                }
                if (i2[1] > maxY) {
                    maxY = i2[1];
                }
            }
        }
    }
    Integer maxX = getCraft().getMinX() + hb.length;
    Integer maxZ = getCraft().getMinZ() + hb[0].length; // safe because if the first x array doesn't have a z array, then it wouldn't be the first x array
    minX = getCraft().getMinX();
    minZ = getCraft().getMinZ();

    int distX = maxX - minX;
    int distZ = maxZ - minZ;

    Player craftPilot = CraftManager.getInstance().getPlayerFromCraft(getCraft());

    if (getCraft().getDisabled() && (!getCraft().getSinking())) {
        failed = true;
        failMessage = String.format(I18nSupport.getInternationalisedString("Craft is disabled!"));
    }

    // blockedByWater=false means an ocean-going vessel
    boolean waterCraft = !getCraft().getType().blockedByWater();

    if (waterCraft) {
        // next figure out the water level by examining blocks next to the outer boundaries of the craft
        for (int posY = maxY; (posY >= minY) && (waterLine == 0); posY--) {
            int posX;
            int posZ;
            posZ = getCraft().getMinZ() - 1;
            for (posX = getCraft().getMinX() - 1; (posX <= maxX + 1) && (waterLine == 0); posX++) {
                if (w.getBlockAt(posX, posY, posZ).getTypeId() == 9) {
                    waterLine = posY;
                }
            }
            posZ = maxZ + 1;
            for (posX = getCraft().getMinX() - 1; (posX <= maxX + 1) && (waterLine == 0); posX++) {
                if (w.getBlockAt(posX, posY, posZ).getTypeId() == 9) {
                    waterLine = posY;
                }
            }
            posX = getCraft().getMinX() - 1;
            for (posZ = getCraft().getMinZ(); (posZ <= maxZ) && (waterLine == 0); posZ++) {
                if (w.getBlockAt(posX, posY, posZ).getTypeId() == 9) {
                    waterLine = posY;
                }
            }
            posX = maxX + 1;
            for (posZ = getCraft().getMinZ(); (posZ <= maxZ) && (waterLine == 0); posZ++) {
                if (w.getBlockAt(posX, posY, posZ).getTypeId() == 9) {
                    waterLine = posY;
                }
            }
        }

        // now add all the air blocks found within the crafts borders below the waterline to the craft blocks so they will be rotated
        HashSet<MovecraftLocation> newHSBlockList = new HashSet<MovecraftLocation>(Arrays.asList(blockList));
        for (int posY = waterLine; posY >= minY; posY--) {
            for (int posX = getCraft().getMinX(); posX <= maxX; posX++) {
                for (int posZ = getCraft().getMinZ(); posZ <= maxZ; posZ++) {
                    if (w.getBlockAt(posX, posY, posZ).getTypeId() == 0) {
                        MovecraftLocation l = new MovecraftLocation(posX, posY, posZ);
                        newHSBlockList.add(l);
                    }
                }
            }
        }
        blockList = newHSBlockList.toArray(new MovecraftLocation[newHSBlockList.size()]);
    }

    // check for fuel, burn some from a furnace if needed. Blocks of coal are supported, in addition to coal and charcoal
    double fuelBurnRate = getCraft().getType().getFuelBurnRate();
    if (fuelBurnRate != 0.0 && getCraft().getSinking() == false) {
        if (getCraft().getBurningFuel() < fuelBurnRate) {
            Block fuelHolder = null;
            for (MovecraftLocation bTest : blockList) {
                Block b = getCraft().getW().getBlockAt(bTest.getX(), bTest.getY(), bTest.getZ());
                if (b.getTypeId() == 61) {
                    InventoryHolder inventoryHolder = (InventoryHolder) b.getState();
                    if (inventoryHolder.getInventory().contains(263)
                            || inventoryHolder.getInventory().contains(173)) {
                        fuelHolder = b;
                    }
                }
            }
            if (fuelHolder == null) {
                failed = true;
                failMessage = String.format(
                        I18nSupport.getInternationalisedString("Translation - Failed Craft out of fuel"));
            } else {
                InventoryHolder inventoryHolder = (InventoryHolder) fuelHolder.getState();
                if (inventoryHolder.getInventory().contains(263)) {
                    ItemStack iStack = inventoryHolder.getInventory()
                            .getItem(inventoryHolder.getInventory().first(263));
                    int amount = iStack.getAmount();
                    if (amount == 1) {
                        inventoryHolder.getInventory().remove(iStack);
                    } else {
                        iStack.setAmount(amount - 1);
                    }
                    getCraft().setBurningFuel(getCraft().getBurningFuel() + 7.0);
                } else {
                    ItemStack iStack = inventoryHolder.getInventory()
                            .getItem(inventoryHolder.getInventory().first(173));
                    int amount = iStack.getAmount();
                    if (amount == 1) {
                        inventoryHolder.getInventory().remove(iStack);
                    } else {
                        iStack.setAmount(amount - 1);
                    }
                    getCraft().setBurningFuel(getCraft().getBurningFuel() + 79.0);

                }
            }
        } else {
            getCraft().setBurningFuel(getCraft().getBurningFuel() - fuelBurnRate);
        }
    }

    // Rotate the block set
    MovecraftLocation[] centeredBlockList = new MovecraftLocation[blockList.length];
    MovecraftLocation[] originalBlockList = blockList.clone();
    HashSet<MovecraftLocation> existingBlockSet = new HashSet<MovecraftLocation>(
            Arrays.asList(originalBlockList));
    Set<MapUpdateCommand> mapUpdates = new HashSet<MapUpdateCommand>();
    HashSet<EntityUpdateCommand> entityUpdateSet = new HashSet<EntityUpdateCommand>();

    boolean townyEnabled = Movecraft.getInstance().getTownyPlugin() != null;
    Set<TownBlock> townBlockSet = new HashSet<TownBlock>();
    TownyWorld townyWorld = null;
    TownyWorldHeightLimits townyWorldHeightLimits = null;

    if (townyEnabled && Settings.TownyBlockMoveOnSwitchPerm) {
        townyWorld = TownyUtils.getTownyWorld(getCraft().getW());
        if (townyWorld != null) {
            townyEnabled = townyWorld.isUsingTowny();
            if (townyEnabled)
                townyWorldHeightLimits = TownyUtils.getWorldLimits(getCraft().getW());
        }
    } else {
        townyEnabled = false;
    }

    // if a subcraft, find the parent craft. If not a subcraft, it is it's own parent
    Craft[] craftsInWorld = CraftManager.getInstance().getCraftsInWorld(getCraft().getW());
    Craft parentCraft = getCraft();
    for (Craft craft : craftsInWorld) {
        if (BlockUtils.arrayContainsOverlap(craft.getBlockList(), originalBlockList) && craft != getCraft()) {
            // found a parent craft
            //            if(craft.isNotProcessing()==false) {
            //               failed=true;
            //               failMessage = String.format( I18nSupport.getInternationalisedString( "Parent Craft is busy" ));
            //               return;
            //            } else {
            //               craft.setProcessing(true); // prevent the parent craft from moving or updating until the subcraft is done
            parentCraft = craft;
            //            }
        }
    }

    int craftMinY = 0;
    int craftMaxY = 0;
    // make the centered block list
    for (int i = 0; i < blockList.length; i++) {
        centeredBlockList[i] = blockList[i].subtract(originPoint);

    }

    for (int i = 0; i < blockList.length; i++) {

        blockList[i] = MathUtils.rotateVec(rotation, centeredBlockList[i]).add(originPoint);
        int typeID = w.getBlockTypeIdAt(blockList[i].getX(), blockList[i].getY(), blockList[i].getZ());

        Material testMaterial = w.getBlockAt(originalBlockList[i].getX(), originalBlockList[i].getY(),
                originalBlockList[i].getZ()).getType();

        if (testMaterial.equals(Material.CHEST) || testMaterial.equals(Material.TRAPPED_CHEST)) {
            if (!checkChests(testMaterial, blockList[i], existingBlockSet)) {
                //prevent chests collision
                failed = true;
                failMessage = String
                        .format(I18nSupport.getInternationalisedString("Rotation - Craft is obstructed")
                                + " @ %d,%d,%d", blockList[i].getX(), blockList[i].getY(), blockList[i].getZ());
                break;
            }
        }
        Location plugLoc = new Location(w, blockList[i].getX(), blockList[i].getY(), blockList[i].getZ());
        if (craftPilot != null) {
            // See if they are permitted to build in the area, if WorldGuard integration is turned on
            if (Movecraft.getInstance().getWorldGuardPlugin() != null
                    && Settings.WorldGuardBlockMoveOnBuildPerm) {
                if (Movecraft.getInstance().getWorldGuardPlugin().canBuild(craftPilot, plugLoc) == false) {
                    failed = true;
                    failMessage = String.format(I18nSupport.getInternationalisedString(
                            "Rotation - Player is not permitted to build in this WorldGuard region")
                            + " @ %d,%d,%d", blockList[i].getX(), blockList[i].getY(), blockList[i].getZ());
                    break;
                }
            }
        }

        Player p;
        if (craftPilot == null) {
            p = getCraft().getNotificationPlayer();
        } else {
            p = craftPilot;
        }
        if (p != null) {
            if (Movecraft.getInstance().getWorldGuardPlugin() != null
                    && Movecraft.getInstance().getWGCustomFlagsPlugin() != null
                    && Settings.WGCustomFlagsUsePilotFlag) {
                LocalPlayer lp = Movecraft.getInstance().getWorldGuardPlugin().wrapPlayer(p);
                WGCustomFlagsUtils WGCFU = new WGCustomFlagsUtils();
                if (!WGCFU.validateFlag(plugLoc, Movecraft.FLAG_ROTATE, lp)) {
                    failed = true;
                    failMessage = String.format(
                            I18nSupport.getInternationalisedString("WGCustomFlags - Rotation Failed")
                                    + " @ %d,%d,%d",
                            blockList[i].getX(), blockList[i].getY(), blockList[i].getZ());
                    break;
                }
            }

            if (townyEnabled) {
                TownBlock townBlock = TownyUtils.getTownBlock(plugLoc);
                if (townBlock != null && !townBlockSet.contains(townBlock)) {
                    if (TownyUtils.validateCraftMoveEvent(p, plugLoc, townyWorld)) {
                        townBlockSet.add(townBlock);
                    } else {
                        int y = plugLoc.getBlockY();
                        boolean oChange = false;
                        if (craftMinY > y) {
                            craftMinY = y;
                            oChange = true;
                        }
                        if (craftMaxY < y) {
                            craftMaxY = y;
                            oChange = true;
                        }
                        if (oChange) {
                            Town town = TownyUtils.getTown(townBlock);
                            if (town != null) {
                                Location locSpawn = TownyUtils.getTownSpawn(townBlock);
                                if (locSpawn != null) {
                                    if (!townyWorldHeightLimits.validate(y, locSpawn.getBlockY())) {
                                        failed = true;
                                    }
                                } else {
                                    failed = true;
                                }
                                if (failed) {
                                    if (Movecraft.getInstance().getWorldGuardPlugin() != null
                                            && Movecraft.getInstance().getWGCustomFlagsPlugin() != null
                                            && Settings.WGCustomFlagsUsePilotFlag) {
                                        LocalPlayer lp = Movecraft.getInstance().getWorldGuardPlugin()
                                                .wrapPlayer(p);
                                        ApplicableRegionSet regions = Movecraft.getInstance()
                                                .getWorldGuardPlugin().getRegionManager(plugLoc.getWorld())
                                                .getApplicableRegions(plugLoc);
                                        if (regions.size() != 0) {
                                            WGCustomFlagsUtils WGCFU = new WGCustomFlagsUtils();
                                            if (WGCFU.validateFlag(plugLoc, Movecraft.FLAG_ROTATE, lp)) {
                                                failed = false;
                                            }
                                        }
                                    }
                                }
                                if (failed) {
                                    failMessage = String.format(
                                            I18nSupport.getInternationalisedString("Towny - Rotation Failed")
                                                    + " %s @ %d,%d,%d",
                                            town.getName(), blockList[i].getX(), blockList[i].getY(),
                                            blockList[i].getZ());
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }

        if (!waterCraft) {
            if ((typeID != 0 && typeID != 34) && !existingBlockSet.contains(blockList[i])) {
                failed = true;
                failMessage = String
                        .format(I18nSupport.getInternationalisedString("Rotation - Craft is obstructed")
                                + " @ %d,%d,%d", blockList[i].getX(), blockList[i].getY(), blockList[i].getZ());
                break;
            } else {
                int id = w.getBlockTypeIdAt(originalBlockList[i].getX(), originalBlockList[i].getY(),
                        originalBlockList[i].getZ());
                byte data = w.getBlockAt(originalBlockList[i].getX(), originalBlockList[i].getY(),
                        originalBlockList[i].getZ()).getData();
                int currentID = w.getBlockTypeIdAt(blockList[i].getX(), blockList[i].getY(),
                        blockList[i].getZ());
                byte currentData = w.getBlockAt(blockList[i].getX(), blockList[i].getY(), blockList[i].getZ())
                        .getData();
                if (BlockUtils.blockRequiresRotation(id)) {
                    data = BlockUtils.rotate(data, id, rotation);
                }
                mapUpdates.add(new MapUpdateCommand(originalBlockList[i], currentID, currentData, blockList[i],
                        id, data, rotation, parentCraft));
            }
        } else {
            // allow watercraft to rotate through water
            if ((typeID != 0 && typeID != 9 && typeID != 34) && !existingBlockSet.contains(blockList[i])) {
                failed = true;
                failMessage = String
                        .format(I18nSupport.getInternationalisedString("Rotation - Craft is obstructed")
                                + " @ %d,%d,%d", blockList[i].getX(), blockList[i].getY(), blockList[i].getZ());
                break;
            } else {
                int id = w.getBlockTypeIdAt(originalBlockList[i].getX(), originalBlockList[i].getY(),
                        originalBlockList[i].getZ());
                byte data = w.getBlockAt(originalBlockList[i].getX(), originalBlockList[i].getY(),
                        originalBlockList[i].getZ()).getData();
                int currentID = w.getBlockTypeIdAt(blockList[i].getX(), blockList[i].getY(),
                        blockList[i].getZ());
                byte currentData = w.getBlockAt(blockList[i].getX(), blockList[i].getY(), blockList[i].getZ())
                        .getData();
                if (BlockUtils.blockRequiresRotation(id)) {
                    data = BlockUtils.rotate(data, id, rotation);
                }
                mapUpdates.add(new MapUpdateCommand(originalBlockList[i], currentID, currentData, blockList[i],
                        id, data, rotation, parentCraft));
            }
        }

    }

    if (!failed) {
        //rotate entities in the craft
        Location tOP = new Location(getCraft().getW(), originPoint.getX(), originPoint.getY(),
                originPoint.getZ());

        List<Entity> eList = null;
        int numTries = 0;

        while ((eList == null) && (numTries < 100)) {
            try {
                eList = getCraft().getW().getEntities();
            } catch (java.util.ConcurrentModificationException e) {
                numTries++;
            }
        }
        Iterator<Entity> i = getCraft().getW().getEntities().iterator();
        while (i.hasNext()) {
            Entity pTest = i.next();
            //            if ( MathUtils.playerIsWithinBoundingPolygon( getCraft().getHitBox(), getCraft().getMinX(), getCraft().getMinZ(), MathUtils.bukkit2MovecraftLoc( pTest.getLocation() ) ) ) {
            if (MathUtils.locIsNearCraftFast(getCraft(), MathUtils.bukkit2MovecraftLoc(pTest.getLocation()))) {
                if (pTest.getType() != org.bukkit.entity.EntityType.DROPPED_ITEM) {
                    // Player is onboard this craft
                    tOP.setX(tOP.getBlockX() + 0.5);
                    tOP.setZ(tOP.getBlockZ() + 0.5);
                    Location playerLoc = pTest.getLocation();
                    // direct control no longer locks the player in place                  
                    //                  if(getCraft().getPilotLocked()==true && pTest==CraftManager.getInstance().getPlayerFromCraft(getCraft())) {
                    //                     playerLoc.setX(getCraft().getPilotLockedX());
                    //                     playerLoc.setY(getCraft().getPilotLockedY());
                    //                     playerLoc.setZ(getCraft().getPilotLockedZ());
                    //                     }
                    Location adjustedPLoc = playerLoc.subtract(tOP);

                    double[] rotatedCoords = MathUtils.rotateVecNoRound(rotation, adjustedPLoc.getX(),
                            adjustedPLoc.getZ());
                    Location rotatedPloc = new Location(getCraft().getW(), rotatedCoords[0], playerLoc.getY(),
                            rotatedCoords[1]);
                    Location newPLoc = rotatedPloc.add(tOP);

                    newPLoc.setPitch(playerLoc.getPitch());
                    float newYaw = playerLoc.getYaw();
                    if (rotation == Rotation.CLOCKWISE) {
                        newYaw = newYaw + 90.0F;
                        if (newYaw >= 360.0F) {
                            newYaw = newYaw - 360.0F;
                        }
                    }
                    if (rotation == Rotation.ANTICLOCKWISE) {
                        newYaw = newYaw - 90;
                        if (newYaw < 0.0F) {
                            newYaw = newYaw + 360.0F;
                        }
                    }
                    newPLoc.setYaw(newYaw);

                    //                  if(getCraft().getPilotLocked()==true && pTest==CraftManager.getInstance().getPlayerFromCraft(getCraft())) {
                    //                     getCraft().setPilotLockedX(newPLoc.getX());
                    //                     getCraft().setPilotLockedY(newPLoc.getY());
                    //                     getCraft().setPilotLockedZ(newPLoc.getZ());
                    //                     }
                    EntityUpdateCommand eUp = new EntityUpdateCommand(pTest.getLocation().clone(), newPLoc,
                            pTest);
                    entityUpdateSet.add(eUp);
                    //                  if(getCraft().getPilotLocked()==true && pTest==CraftManager.getInstance().getPlayerFromCraft(getCraft())) {
                    //                     getCraft().setPilotLockedX(newPLoc.getX());
                    //                     getCraft().setPilotLockedY(newPLoc.getY());
                    //                     getCraft().setPilotLockedZ(newPLoc.getZ());
                    //                  }
                } else {
                    //   pTest.remove();   removed to test cleaner fragile item removal
                }
            }

        }

        /*         //update player spawn locations if they spawned where the ship used to be
                 for(Player p : Movecraft.getInstance().getServer().getOnlinePlayers()) {
                    if(p.getBedSpawnLocation()!=null) {
                       if( MathUtils.playerIsWithinBoundingPolygon( getCraft().getHitBox(), getCraft().getMinX(), getCraft().getMinZ(), MathUtils.bukkit2MovecraftLoc( p.getBedSpawnLocation() ) ) ) {
          Location spawnLoc = p.getBedSpawnLocation();
          Location adjustedPLoc = spawnLoc.subtract( tOP ); 
                
          double[] rotatedCoords = MathUtils.rotateVecNoRound( rotation, adjustedPLoc.getX(), adjustedPLoc.getZ() );
          Location rotatedPloc = new Location( getCraft().getW(), rotatedCoords[0], spawnLoc.getY(), rotatedCoords[1] );
          Location newBedSpawn = rotatedPloc.add( tOP );
                
          p.setBedSpawnLocation(newBedSpawn, true);
                       }
                    }
                 }*/

        // Calculate air changes
        List<MovecraftLocation> airLocation = ListUtils.subtract(Arrays.asList(originalBlockList),
                Arrays.asList(blockList));

        for (MovecraftLocation l1 : airLocation) {
            if (waterCraft) {
                // if its below the waterline, fill in with water. Otherwise fill in with air.
                if (l1.getY() <= waterLine) {
                    mapUpdates.add(new MapUpdateCommand(l1, 9, (byte) 0, parentCraft));
                } else {
                    mapUpdates.add(new MapUpdateCommand(l1, 0, (byte) 0, parentCraft));
                }
            } else {
                mapUpdates.add(new MapUpdateCommand(l1, 0, (byte) 0, parentCraft));
            }
        }

        // rotate scheduled block changes
        HashMap<MapUpdateCommand, Long> newScheduledBlockChanges = new HashMap<MapUpdateCommand, Long>();
        HashMap<MapUpdateCommand, Long> oldScheduledBlockChanges = getCraft().getScheduledBlockChanges();
        for (MapUpdateCommand muc : oldScheduledBlockChanges.keySet()) {
            MovecraftLocation newLoc = muc.getNewBlockLocation();
            newLoc = newLoc.subtract(originPoint);
            newLoc = MathUtils.rotateVec(rotation, newLoc).add(originPoint);
            Long newTime = System.currentTimeMillis() + 5000;
            MapUpdateCommand newMuc = new MapUpdateCommand(newLoc, muc.getTypeID(), muc.getDataID(),
                    parentCraft);
            newScheduledBlockChanges.put(newMuc, newTime);
        }
        this.scheduledBlockChanges = newScheduledBlockChanges;

        MapUpdateCommand[] updateArray = mapUpdates.toArray(new MapUpdateCommand[1]);
        //            MapUpdateManager.getInstance().sortUpdates(updateArray);
        this.updates = updateArray;
        this.entityUpdates = entityUpdateSet.toArray(new EntityUpdateCommand[1]);

        maxX = null;
        maxZ = null;
        minX = null;
        minZ = null;

        for (MovecraftLocation l : blockList) {
            if (maxX == null || l.getX() > maxX) {
                maxX = l.getX();
            }
            if (maxZ == null || l.getZ() > maxZ) {
                maxZ = l.getZ();
            }
            if (minX == null || l.getX() < minX) {
                minX = l.getX();
            }
            if (minZ == null || l.getZ() < minZ) {
                minZ = l.getZ();
            }
        }

        // Rerun the polygonal bounding formula for the newly formed craft
        int sizeX, sizeZ;
        sizeX = (maxX - minX) + 1;
        sizeZ = (maxZ - minZ) + 1;

        int[][][] polygonalBox = new int[sizeX][][];

        for (MovecraftLocation l : blockList) {
            if (polygonalBox[l.getX() - minX] == null) {
                polygonalBox[l.getX() - minX] = new int[sizeZ][];
            }

            if (polygonalBox[l.getX() - minX][l.getZ() - minZ] == null) {

                polygonalBox[l.getX() - minX][l.getZ() - minZ] = new int[2];
                polygonalBox[l.getX() - minX][l.getZ() - minZ][0] = l.getY();
                polygonalBox[l.getX() - minX][l.getZ() - minZ][1] = l.getY();

            } else {
                minY = polygonalBox[l.getX() - minX][l.getZ() - minZ][0];
                maxY = polygonalBox[l.getX() - minX][l.getZ() - minZ][1];

                if (l.getY() < minY) {
                    polygonalBox[l.getX() - minX][l.getZ() - minZ][0] = l.getY();
                }
                if (l.getY() > maxY) {
                    polygonalBox[l.getX() - minX][l.getZ() - minZ][1] = l.getY();
                }

            }

        }

        this.hitbox = polygonalBox;
        if (getCraft().getCruising()) {
            if (rotation == Rotation.ANTICLOCKWISE) {
                // ship faces west
                if (getCraft().getCruiseDirection() == 0x5) {
                    getCraft().setCruiseDirection((byte) 0x2);
                } else
                // ship faces east
                if (getCraft().getCruiseDirection() == 0x4) {
                    getCraft().setCruiseDirection((byte) 0x3);
                } else
                // ship faces north
                if (getCraft().getCruiseDirection() == 0x2) {
                    getCraft().setCruiseDirection((byte) 0x4);
                } else
                // ship faces south
                if (getCraft().getCruiseDirection() == 0x3) {
                    getCraft().setCruiseDirection((byte) 0x5);
                }
            } else if (rotation == Rotation.CLOCKWISE) {
                // ship faces west
                if (getCraft().getCruiseDirection() == 0x5) {
                    getCraft().setCruiseDirection((byte) 0x3);
                } else
                // ship faces east
                if (getCraft().getCruiseDirection() == 0x4) {
                    getCraft().setCruiseDirection((byte) 0x2);
                } else
                // ship faces north
                if (getCraft().getCruiseDirection() == 0x2) {
                    getCraft().setCruiseDirection((byte) 0x5);
                } else
                // ship faces south
                if (getCraft().getCruiseDirection() == 0x3) {
                    getCraft().setCruiseDirection((byte) 0x4);
                }
            }
        }

        // if you rotated a subcraft, update the parent with the new blocks
        if (this.isSubCraft) {
            // also find the furthest extent from center and notify the player of the new direction
            int farthestX = 0;
            int farthestZ = 0;
            for (MovecraftLocation loc : blockList) {
                if (Math.abs(loc.getX() - originPoint.getX()) > Math.abs(farthestX))
                    farthestX = loc.getX() - originPoint.getX();
                if (Math.abs(loc.getZ() - originPoint.getZ()) > Math.abs(farthestZ))
                    farthestZ = loc.getZ() - originPoint.getZ();
            }
            if (Math.abs(farthestX) > Math.abs(farthestZ)) {
                if (farthestX > 0) {
                    if (getCraft().getNotificationPlayer() != null)
                        getCraft().getNotificationPlayer().sendMessage("The farthest extent now faces East");
                } else {
                    if (getCraft().getNotificationPlayer() != null)
                        getCraft().getNotificationPlayer().sendMessage("The farthest extent now faces West");
                }
            } else {
                if (farthestZ > 0) {
                    if (getCraft().getNotificationPlayer() != null)
                        getCraft().getNotificationPlayer().sendMessage("The farthest extent now faces South");
                } else {
                    if (getCraft().getNotificationPlayer() != null)
                        getCraft().getNotificationPlayer().sendMessage("The farthest extent now faces North");
                }
            }

            craftsInWorld = CraftManager.getInstance().getCraftsInWorld(getCraft().getW());
            for (Craft craft : craftsInWorld) {
                if (BlockUtils.arrayContainsOverlap(craft.getBlockList(), originalBlockList)
                        && craft != getCraft()) {
                    List<MovecraftLocation> parentBlockList = ListUtils
                            .subtract(Arrays.asList(craft.getBlockList()), Arrays.asList(originalBlockList));
                    parentBlockList.addAll(Arrays.asList(blockList));
                    craft.setBlockList(parentBlockList.toArray(new MovecraftLocation[1]));

                    // Rerun the polygonal bounding formula for the parent craft
                    Integer parentMaxX = null;
                    Integer parentMaxZ = null;
                    Integer parentMinX = null;
                    Integer parentMinZ = null;
                    for (MovecraftLocation l : parentBlockList) {
                        if (parentMaxX == null || l.getX() > parentMaxX) {
                            parentMaxX = l.getX();
                        }
                        if (parentMaxZ == null || l.getZ() > parentMaxZ) {
                            parentMaxZ = l.getZ();
                        }
                        if (parentMinX == null || l.getX() < parentMinX) {
                            parentMinX = l.getX();
                        }
                        if (parentMinZ == null || l.getZ() < parentMinZ) {
                            parentMinZ = l.getZ();
                        }
                    }
                    int parentSizeX, parentSizeZ;
                    parentSizeX = (parentMaxX - parentMinX) + 1;
                    parentSizeZ = (parentMaxZ - parentMinZ) + 1;
                    int[][][] parentPolygonalBox = new int[parentSizeX][][];
                    for (MovecraftLocation l : parentBlockList) {
                        if (parentPolygonalBox[l.getX() - parentMinX] == null) {
                            parentPolygonalBox[l.getX() - parentMinX] = new int[parentSizeZ][];
                        }
                        if (parentPolygonalBox[l.getX() - parentMinX][l.getZ() - parentMinZ] == null) {
                            parentPolygonalBox[l.getX() - parentMinX][l.getZ() - parentMinZ] = new int[2];
                            parentPolygonalBox[l.getX() - parentMinX][l.getZ() - parentMinZ][0] = l.getY();
                            parentPolygonalBox[l.getX() - parentMinX][l.getZ() - parentMinZ][1] = l.getY();
                        } else {
                            int parentMinY = parentPolygonalBox[l.getX() - parentMinX][l.getZ()
                                    - parentMinZ][0];
                            int parentMaxY = parentPolygonalBox[l.getX() - parentMinX][l.getZ()
                                    - parentMinZ][1];

                            if (l.getY() < parentMinY) {
                                parentPolygonalBox[l.getX() - parentMinX][l.getZ() - parentMinZ][0] = l.getY();
                            }
                            if (l.getY() > parentMaxY) {
                                parentPolygonalBox[l.getX() - parentMinX][l.getZ() - parentMinZ][1] = l.getY();
                            }
                        }
                    }
                    craft.setMinX(parentMinX);
                    craft.setMinZ(parentMinZ);
                    craft.setHitBox(parentPolygonalBox);
                }
            }
        }

    } else { // this else is for "if(!failed)"
        if (this.isSubCraft) {
            if (parentCraft != getCraft()) {
                parentCraft.setProcessing(false);
            }
        }
    }
}