Example usage for java.util Arrays copyOfRange

List of usage examples for java.util Arrays copyOfRange

Introduction

In this page you can find the example usage for java.util Arrays copyOfRange.

Prototype

public static boolean[] copyOfRange(boolean[] original, int from, int to) 

Source Link

Document

Copies the specified range of the specified array into a new array.

Usage

From source file:com.turbospaces.spaces.SpaceReceiveAdapter.java

@Override
public void receive(final Message msg) {
    final byte[] data = msg.getBuffer();
    final ObjectBuffer objectBuffer = new ObjectBuffer(jSpace.getSpaceConfiguration().getKryo());
    final Address nodeRaised = msg.getSrc();

    final MethodCall methodCall = (MethodCall) objectBuffer.readClassAndObject(data);
    final short id = methodCall.getMethodId();

    logger.debug("received {} from {}", methodCall, nodeRaised);

    if (id == SpaceMethodsMapping.BEGIN_TRANSACTION.ordinal())
        sendResponseBackAfterExecution(methodCall, new Runnable() {
            @Override// w w w  .j a  va  2 s.  co m
            public void run() {
                /**
                 * 1. read transaction timeout
                 * 2. create local durable transaction for remote client and assign id
                 * 3. propagate remote transaction timeout and apply to local transaction
                 * 4. send transaction id back to client
                 */
                BeginTransactionMethodCall beginTransactionMethodCall = (BeginTransactionMethodCall) methodCall;
                long transactionTimeout = beginTransactionMethodCall.getTransactionTimeout();
                SpaceTransactionHolder spaceTransactionHolder = new SpaceTransactionHolder();
                spaceTransactionHolder.setSynchronizedWithTransaction(true);
                spaceTransactionHolder.setTimeoutInMillis(transactionTimeout);
                TransactionModificationContext mc = new TransactionModificationContext();
                mc.setProxyMode(true);
                spaceTransactionHolder.setModificationContext(mc);
                modificationContextFor(nodeRaised).put(mc.getTransactionId(), spaceTransactionHolder);
                methodCall.setResponseBody(objectBuffer.writeObjectData(mc.getTransactionId()));
            }
        }, nodeRaised, objectBuffer);
    else if (id == SpaceMethodsMapping.COMMIT_TRANSACTION.ordinal())
        sendResponseBackAfterExecution(methodCall, new Runnable() {
            @Override
            public void run() {
                CommitRollbackMethodCall commitMethodCall = (CommitRollbackMethodCall) methodCall;
                try {
                    SpaceTransactionHolder th = modificationContextFor(nodeRaised)
                            .getIfPresent(commitMethodCall.getTransactionId());
                    Preconditions.checkState(th != null, "unable to find transaction with id = %s for commit",
                            commitMethodCall.getTransactionId());
                    jSpace.syncTx(th.getModificationContext(), true);
                } finally {
                    durableTransactions.remove(commitMethodCall.getTransactionId());
                }
            }
        }, nodeRaised, objectBuffer);
    else if (id == SpaceMethodsMapping.ROLLBACK_TRANSACTION.ordinal())
        sendResponseBackAfterExecution(methodCall, new Runnable() {
            @Override
            public void run() {
                CommitRollbackMethodCall commitMethodCall = (CommitRollbackMethodCall) methodCall;
                try {
                    SpaceTransactionHolder th = modificationContextFor(nodeRaised)
                            .getIfPresent(commitMethodCall.getTransactionId());
                    Preconditions.checkState(th != null, "unable to find transaction with id = %s for rollback",
                            commitMethodCall.getTransactionId());
                    jSpace.syncTx(th.getModificationContext(), false);
                } finally {
                    durableTransactions.remove(commitMethodCall.getTransactionId());
                }
            }
        }, nodeRaised, objectBuffer);
    else if (id == SpaceMethodsMapping.WRITE.ordinal())
        sendResponseBackAfterExecution(methodCall, new Runnable() {
            @Override
            public void run() {
                WriteMethodCall writeMethodCall = (WriteMethodCall) methodCall;
                byte[] entityAndClassData = writeMethodCall.getEntity();
                ByteBuffer byteBuffer = ByteBuffer.wrap(entityAndClassData);

                int modifiers = writeMethodCall.getModifiers();
                int timeout = writeMethodCall.getTimeout();
                int timeToLive = writeMethodCall.getTimeToLive();

                /**
                 * 1. read registered class (without actual data)
                 * 2. get the actual type of the remote entry
                 * 3. copy serialized entry state from the byte buffer, omit redundant serialization later
                 * 4. find appropriate transaction modification context if any
                 * 5. call write method itself
                 */
                RegisteredClass entryClass = jSpace.getSpaceConfiguration().getKryo().readClass(byteBuffer);
                Class<?> entryType = entryClass.getType();
                byte[] entityData = Arrays.copyOfRange(byteBuffer.array(), byteBuffer.position(),
                        byteBuffer.capacity());
                Object entry = jSpace.getSpaceConfiguration().getKryo().readObjectData(byteBuffer, entryType);

                SpaceTransactionHolder holder = null;
                if (writeMethodCall.getTransactionId() != 0)
                    holder = modificationContextFor(nodeRaised)
                            .getIfPresent(writeMethodCall.getTransactionId());

                jSpace.write(holder, entry, entityData, timeToLive, timeout, modifiers);
                writeMethodCall.reset();
            }
        }, nodeRaised, objectBuffer);
    else if (id == SpaceMethodsMapping.FETCH.ordinal())
        sendResponseBackAfterExecution(methodCall, new Runnable() {
            @Override
            public void run() {
                FetchMethodCall fetchMethodCall = (FetchMethodCall) methodCall;
                byte[] entityData = fetchMethodCall.getEntity();

                int originalModifiers = fetchMethodCall.getModifiers();
                int timeout = fetchMethodCall.getTimeout();
                int maxResults = fetchMethodCall.getMaxResults();
                Object template = objectBuffer.readClassAndObject(entityData);
                int modifiers = originalModifiers | JSpace.RETURN_AS_BYTES;

                SpaceTransactionHolder holder = null;
                if (fetchMethodCall.getTransactionId() != 0)
                    holder = modificationContextFor(nodeRaised)
                            .getIfPresent(fetchMethodCall.getTransactionId());

                ByteBuffer[] buffers = (ByteBuffer[]) jSpace.fetch(holder, template, timeout, maxResults,
                        modifiers);
                if (buffers != null) {
                    byte[][] response = new byte[buffers.length][];
                    for (int i = 0; i < buffers.length; i++) {
                        ByteBuffer buffer = buffers[i];
                        response[i] = buffer.array();
                    }
                    fetchMethodCall.setResponseBody(objectBuffer.writeObjectData(response));
                }
                fetchMethodCall.reset();
            }
        }, nodeRaised, objectBuffer);
    else if (id == SpaceMethodsMapping.NOTIFY.ordinal())
        sendResponseBackAfterExecution(methodCall, new Runnable() {
            @Override
            public void run() {
                NotifyListenerMethodCall registerMethodCall = (NotifyListenerMethodCall) methodCall;
                byte[] entityData = registerMethodCall.getEntity();

                int originalModifiers = registerMethodCall.getModifiers();
                Object template = objectBuffer.readClassAndObject(entityData);
                int modifiers = originalModifiers | JSpace.RETURN_AS_BYTES;
                jSpace.notify(template, new SpaceNotificationListener() {

                    @Override
                    public void handleNotification(final Object entity, final SpaceOperation operation) {
                        ObjectBuffer innerObjectBuffer = new ObjectBuffer(
                                jSpace.getSpaceConfiguration().getKryo());
                        sendResponseBackAfterExecution(methodCall, new Runnable() {
                            @Override
                            public void run() {
                                NotifyListenerMethodCall methodCall = new NotifyListenerMethodCall();
                                methodCall.setEntity(((ByteBuffer) entity).array());
                                methodCall.setOperation(operation);
                            }
                        }, nodeRaised, innerObjectBuffer);
                    }
                }, modifiers);
            }
        }, nodeRaised, objectBuffer);
    else if (id == SpaceMethodsMapping.SIZE.ordinal())
        sendResponseBackAfterExecution(methodCall, new Runnable() {
            @Override
            public void run() {
                methodCall.setResponseBody(objectBuffer.writeObjectData(jSpace.size()));
            }
        }, nodeRaised, objectBuffer);
    else if (id == SpaceMethodsMapping.MB_USED.ordinal())
        sendResponseBackAfterExecution(methodCall, new Runnable() {
            @Override
            public void run() {
                methodCall.setResponseBody(objectBuffer.writeObjectData(jSpace.mbUsed()));
            }
        }, nodeRaised, objectBuffer);
    else if (id == SpaceMethodsMapping.EVICT_ELEMENTS.ordinal())
        sendResponseBackAfterExecution(methodCall, new Runnable() {
            @Override
            public void run() {
                EvictElementsMethodCall evictElementsMethodCall = (EvictElementsMethodCall) methodCall;
                methodCall.setResponseBody(objectBuffer
                        .writeObjectData(jSpace.evictElements(evictElementsMethodCall.getElements())));
            }
        }, nodeRaised, objectBuffer);
    else if (id == SpaceMethodsMapping.EVICT_PERCENTAGE.ordinal())
        sendResponseBackAfterExecution(methodCall, new Runnable() {
            @Override
            public void run() {
                EvictPercentageMethodCall evictPercentageMethodCall = (EvictPercentageMethodCall) methodCall;
                methodCall.setResponseBody(objectBuffer
                        .writeObjectData(jSpace.evictPercentage(evictPercentageMethodCall.getPercentage())));
            }
        }, nodeRaised, objectBuffer);
    else if (id == SpaceMethodsMapping.EVICT_ALL.ordinal())
        sendResponseBackAfterExecution(methodCall, new Runnable() {
            @Override
            public void run() {
                methodCall.setResponseBody(objectBuffer.writeObjectData(jSpace.evictAll()));
            }
        }, nodeRaised, objectBuffer);
    else if (id == SpaceMethodsMapping.SPACE_TOPOLOGY.ordinal())
        sendResponseBackAfterExecution(methodCall, new Runnable() {
            @Override
            public void run() {
                methodCall.setResponseBody(
                        objectBuffer.writeObjectData(jSpace.getSpaceConfiguration().getTopology()));
            }
        }, nodeRaised, objectBuffer);
}

From source file:com.wallellen.wechat.common.util.crypto.WxCryptUtil.java

/**
 * .//  w w  w.  ja  v  a2  s .c  om
 *
 * @param cipherText ?
 * @return 
 */
public String decrypt(String cipherText) {
    byte[] original;
    try {
        // ?AESCBC?
        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        SecretKeySpec key_spec = new SecretKeySpec(aesKey, "AES");
        IvParameterSpec iv = new IvParameterSpec(Arrays.copyOfRange(aesKey, 0, 16));
        cipher.init(Cipher.DECRYPT_MODE, key_spec, iv);

        // BASE64?
        byte[] encrypted = Base64.decodeBase64(cipherText);

        // 
        original = cipher.doFinal(encrypted);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    String xmlContent, from_appid;
    try {
        // ?
        byte[] bytes = PKCS7Encoder.decode(original);

        // 16??,?AppId
        byte[] networkOrder = Arrays.copyOfRange(bytes, 16, 20);

        int xmlLength = bytesNetworkOrder2Number(networkOrder);

        xmlContent = new String(Arrays.copyOfRange(bytes, 20, 20 + xmlLength), CHARSET);
        from_appid = new String(Arrays.copyOfRange(bytes, 20 + xmlLength, bytes.length), CHARSET);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    // appid??
    if (!from_appid.equals(appidOrCorpid)) {
        throw new RuntimeException("AppID?");
    }

    return xmlContent;

}

From source file:edu.harvard.hms.dbmi.bd2k.irct.ri.i2b2.I2B2XMLResourceImplementation.java

@Override
public List<Entity> getPathRelationship(Entity path, OntologyRelationship relationship, SecureSession session)
        throws ResourceInterfaceException {
    List<Entity> entities = new ArrayList<Entity>();
    // Build//from   ww w. j av  a 2  s  .co  m
    HttpClient client = createClient(session);
    String basePath = path.getPui();
    String[] pathComponents = basePath.split("/");

    try {
        if (relationship == I2B2OntologyRelationship.CHILD) {
            // If first then get projects
            if (pathComponents.length == 2) {
                pmCell = createPMCell();
                ConfigureType configureType = pmCell.getUserConfiguration(client, null,
                        new String[] { "undefined" });
                for (ProjectType pt : configureType.getUser().getProject()) {
                    Entity entity = new Entity();
                    if (pt.getPath() == null) {
                        entity.setPui(path.getPui() + "/" + pt.getName());
                    } else {
                        entity.setPui(path.getPui() + pt.getPath());
                    }
                    entity.setDisplayName(pt.getName());
                    entity.setName(pt.getId());
                    entity.setDescription(pt.getDescription());
                    entities.add(entity);
                }

            } else {
                ontCell = createOntCell(pathComponents[2]);

                ConceptsType conceptsType = null;

                if (pathComponents.length == 3) {
                    // If beyond second then get ontology categories
                    conceptsType = ontCell.getCategories(client, false, false, true, "core");
                } else {
                    // If second then get categories
                    String myPath = "\\";
                    for (String pathComponent : Arrays.copyOfRange(pathComponents, 3, pathComponents.length)) {
                        myPath += "\\" + pathComponent;
                    }
                    basePath = pathComponents[0] + "/" + pathComponents[1] + "/" + pathComponents[2];

                    conceptsType = ontCell.getChildren(client, myPath, false, false, false, -1, "core");

                }
                // Convert ConceptsType to Entities
                entities = convertConceptsTypeToEntities(basePath, conceptsType);
            }

        } else if (relationship == I2B2OntologyRelationship.MODIFIER) {
            String resourcePath = getResourcePathFromPUI(basePath);

            if (resourcePath == null) {
                return entities;
            }

            if (resourcePath.lastIndexOf('\\') != resourcePath.length() - 1) {
                resourcePath += '\\';
            }
            ontCell = createOntCell(pathComponents[2]);
            ModifiersType modifiersType = ontCell.getModifiers(client, false, false, null, -1, resourcePath,
                    false, null);
            entities = convertModifiersTypeToEntities(basePath, modifiersType);
        } else if (relationship == I2B2OntologyRelationship.TERM) {
            String resourcePath = getResourcePathFromPUI(basePath);

            if (resourcePath == null) {
                return entities;
            }

            if (resourcePath.lastIndexOf('\\') != resourcePath.length() - 1) {
                resourcePath += '\\';
            }
            ontCell = createOntCell(pathComponents[2]);

            ConceptsType conceptsType = null;

            conceptsType = ontCell.getTermInfo(client, true, resourcePath, true, -1, true, "core");
            entities = convertConceptsTypeToEntities(basePath, conceptsType);
        } else {
            throw new ResourceInterfaceException(relationship.toString() + " not supported by this resource");
        }
    } catch (Exception e) {
        throw new ResourceInterfaceException(e.getMessage());
    }

    return entities;
}

From source file:org.elasticsearch.river.jolokia.strategy.simple.SimpleRiverSource.java

private static String join(String del, String[] array) {
    if (array.length > 1) {
        return array[0] + del + join(del, Arrays.copyOfRange(array, 1, array.length));
    }//from   w  w  w. j a v  a2 s  .  com
    return array[0];
}

From source file:com.opengamma.maths.lowlevelapi.datatypes.primitive.CompressedSparseRowFormatMatrix.java

@Override
public double[] getRowElements(int index) {
    double[] tmp = new double[_cols];
    int ptr = 0;//  w  w w  .  jav  a 2  s . com
    for (int i = _rowPtr[index]; i <= _rowPtr[index + 1] - 1; i++) { // loops through elements of correct row
        tmp[ptr] = _values[i];
        ptr++;
    }
    return Arrays.copyOfRange(tmp, 0, ptr);
}

From source file:eu.europeana.uim.gui.cp.server.RetrievalServiceImpl.java

@Override
public MetaDataResultDTO getRecordsForCollection(String collectionId, int offset, int maxSize,
        String constraint) {//from  w w  w. ja v a 2  s  .  co  m
    StorageEngine<String> storage = (StorageEngine<String>) getEngine().getRegistry().getStorageEngine();
    if (storage == null) {
        log.log(Level.SEVERE, "Storage connection is null!");
        return null;
    }

    String recordId = null;
    if (!constraint.equals("")) {
        recordId = constraint;
    }

    int maxNumber = 0;
    List<MetaDataRecord<String>> metaDataRecords = new ArrayList<MetaDataRecord<String>>();
    if (recordId == null) {
        Collection<String> collection = null;
        try {
            collection = storage.getCollection(collectionId);
        } catch (Throwable t) {
            log.log(Level.WARNING, "Could not retrieve collection for id '" + collectionId + "'!", t);
        }

        if (collection != null) {
            String[] recordIds = null;
            try {
                recordIds = storage.getByCollection(collection);
                maxNumber = recordIds.length;
            } catch (Throwable t) {
                log.log(Level.WARNING, "Could not retrieve records for collection '" + collectionId + "'!", t);
                maxNumber = -1;
            }

            if (recordIds != null && recordIds.length > 0) {
                Arrays.sort(recordIds);
                String[] subset = Arrays.copyOfRange(recordIds, Math.min(offset, recordIds.length - 1),
                        Math.min(offset + maxSize, recordIds.length));

                try {
                    metaDataRecords = storage.getMetaDataRecords(Arrays.asList(subset));
                } catch (Throwable t) {
                    log.log(Level.WARNING,
                            "Could not retrieve records for Ids '" + Arrays.toString(subset) + "'!", t);
                    maxNumber = -1;
                }
            }
        }
    } else {
        metaDataRecords = new ArrayList<MetaDataRecord<String>>();
        try {
            metaDataRecords.add(storage.getMetaDataRecord(recordId));
            maxNumber = 1;
        } catch (Throwable t) {
            log.log(Level.WARNING, "Could not retrieve record with Id '" + recordId + "'!", t);
        }
    }

    List<MetaDataRecordDTO> results = new ArrayList<MetaDataRecordDTO>();
    for (MetaDataRecord<String> metaDataRecord : metaDataRecords) {
        if (metaDataRecord != null && metaDataRecord.getId() != null) {
            MetaDataRecordDTO record = new MetaDataRecordDTO();
            record.setId(metaDataRecord.getId());

            try {
                Status status = metaDataRecord.getFirstValue(EuropeanaModelRegistry.STATUS);

                if (status != null && status.equals(Status.DELETED)) {
                    record.setDeleted(true);
                }

                String creationDate = metaDataRecord.getFirstValue(EuropeanaModelRegistry.UIMINGESTIONDATE);

                record.setImportuimdate(creationDate);

                String updateDate = metaDataRecord.getFirstValue(EuropeanaModelRegistry.UIMUPDATEDDATE);

                record.setUpdateuimdate(updateDate);

                Long initialsaveDate = metaDataRecord.getFirstValue(EuropeanaModelRegistry.INITIALSAVE);

                if (initialsaveDate != null) {
                    Date tmpdate = new Date(initialsaveDate);
                    record.setFirstingestiondate(tmpdate.toString());
                }

                Long updatesaveDate = metaDataRecord.getFirstValue(EuropeanaModelRegistry.UPDATEDSAVE);

                if (updatesaveDate != null) {
                    Date tmpdate = new Date(updatesaveDate);
                    record.setIngestionupdatedate(tmpdate.toString());
                }

                String edmxml = metaDataRecord.getFirstValue(EuropeanaModelRegistry.EDMRECORD);

                if (edmxml != null) {
                    RDF rdf = (RDF) uctx.unmarshalDocument(new StringReader(edmxml));

                    ProxyType cho = rdf.getProxyList().get(0);

                    List<eu.europeana.corelib.definitions.jibx.EuropeanaType.Choice> dctypelist = cho
                            .getChoiceList();
                    if (dctypelist != null) {
                        for (eu.europeana.corelib.definitions.jibx.EuropeanaType.Choice dcchoice : dctypelist) {

                            if (dcchoice.ifTitle()) {
                                record.setTitle(dcchoice.getTitle().getString());
                            }
                        }
                    }
                }

            } catch (JiBXException e) {

                e.printStackTrace();
            }

            results.add(record);
        }
    }

    int deleted_records = 0;
    int active_records = maxNumber;

    Collection<String> collection;
    try {
        collection = storage.getCollection(collectionId);
        deleted_records = collection.getValue("Deleted") == null ? 0
                : Integer.parseInt(collection.getValue("Deleted"));
        active_records = maxNumber - deleted_records;
    } catch (StorageEngineException e) {
        e.printStackTrace();
    }

    MetaDataResultDTO response = new MetaDataResultDTO(results, maxNumber, active_records, deleted_records);

    return response;
}

From source file:com.opengamma.maths.lowlevelapi.datatypes.primitive.SparseCoordinateFormatMatrix.java

/**
 * {@inheritDoc}/* w  w  w  .j  a va2s.  co m*/
 */
@Override
public double[] getRowElements(int index) {
    double[] tmp = new double[_cols]; //overkill
    int ptr = 0;
    // brute force
    for (int i = 0; i < _y.length; i++) {
        if (_y[i] == index) {
            tmp[ptr] = _values[i];
            ptr++;
        }
    }
    return Arrays.copyOfRange(tmp, 0, ptr);
}

From source file:hivemall.topicmodel.ProbabilisticTopicModelBaseUDTF.java

@VisibleForTesting
void finalizeTraining() throws HiveException {
    if (model.getDocCount() == 0L) {
        this.model = null;
        return;//w  w  w . j  ava  2 s .  c  om
    }
    if (miniBatchCount > 0) { // update for remaining samples
        model.train(Arrays.copyOfRange(miniBatch, 0, miniBatchCount));
    }
    if (iterations > 1) {
        runIterativeTraining(iterations);
    }
}

From source file:net.dmulloy2.ultimatearena.types.ArenaConfig.java

/**
 * Loads this config from a given file.//from  www  .j  a va 2s  .co  m
 *
 * @param file File to load from
 * @param def Parent config
 * @return True if loading was successful, false if not
 */
public final boolean load(File file, ArenaConfig def) {
    Validate.isTrue(!loaded, "This config has already been loaded!");
    Validate.notNull(file, "file cannot be null!");
    Validate.notNull(def, "def cannot be null!");

    try {
        YamlConfiguration config = new YamlConfiguration();
        config.load(file);

        Map<String, Object> values = config.getValues(false);
        this.allowTeamKilling = getBoolean(values, "allowTeamKilling", def.isAllowTeamKilling());
        this.countMobKills = getBoolean(values, "countMobKills", def.isCountMobKills());
        this.canModifyWorld = getBoolean(values, "canModifyWorld", def.isCanModifyWorld());
        this.unlimitedAmmo = getBoolean(values, "unlimitedAmmo", def.isUnlimitedAmmo());
        this.rewardBasedOnXp = getBoolean(values, "rewardBasedOnXp", def.isRewardBasedOnXp());
        this.giveRewards = getBoolean(values, "giveRewards", def.isGiveRewards());
        this.forceBalance = getBoolean(values, "forceBalance", def.isForceBalance());
        this.joinInProgress = getBoolean(values, "joinInProgress", def.isJoinInProgress());

        if (this.preserveMobs = getBoolean(values, "preserveMobs", def.isPreserveMobs()))
            Global.mobPreservation = true;

        this.gameTime = getInt(values, "gameTime", def.getGameTime());
        this.lobbyTime = getInt(values, "lobbyTime", def.getLobbyTime());
        this.maxDeaths = Math.max(1, getInt(values, "maxDeaths", def.getMaxDeaths()));
        this.maxPlayers = getInt(values, "maxPlayers", def.getMaxPlayers());
        this.minPlayers = Math.max(1, getInt(values, "minPlayers", def.getMinPlayers()));

        this.defaultClass = getString(values, "defaultClass", def.getDefaultClass());

        this.cashReward = getDouble(values, "cashReward", def.getCashReward());

        WinCondition condition = WinCondition.fromConfig(getString(values, "winCondition", "default"));
        if (condition != null)
            this.winCondition = condition;

        if (giveRewards) {
            if (isSet(values, "rewards")) {
                this.rewards = ItemUtil.readItems(getStringList(values, "rewards"), plugin);
            } else {
                this.rewards = def.getRewards();
            }

            this.scaledRewards = new ArrayList<>();
            if (isSet(values, "scaledRewards")) {
                for (String string : getStringList(values, "scaledRewards")) {
                    ScaledReward reward = ScaledReward.fromString(string);
                    if (reward != null)
                        scaledRewards.add(reward);
                }
            } else {
                if (rewardBasedOnXp) {
                    for (ItemStack item : rewards) {
                        ScaledReward reward = new ScaledReward(item, 200.0D);
                        scaledRewards.add(reward);
                    }
                } else {
                    this.scaledRewards = def.getScaledRewards();
                }
            }
        }

        if (isSet(values, "clearMaterials")) {
            this.clearMaterials = MaterialUtil.fromStrings(getStringList(values, "clearMaterials"));
        } else {
            this.clearMaterials = def.getClearMaterials();
        }

        this.blacklistedClasses = getList(values, "blacklistedClasses", def.getBlacklistedClasses());
        this.whitelistedClasses = getList(values, "whitelistedClasses", def.getWhitelistedClasses());

        this.killStreaks = def.getKillStreaks();
        if (isSet(values, "killStreaks")) {
            this.killStreaks = new LinkedHashMap<>();

            for (Entry<String, Object> entry : getSection(values, "killStreaks").entrySet()) {
                int kills = NumberUtil.toInt(entry.getKey());
                if (kills < 0)
                    continue;

                List<KillStreak> streaks = new ArrayList<>();

                @SuppressWarnings("unchecked")
                List<String> list = (List<String>) entry.getValue();
                for (String string : list) {
                    string = string.replaceAll("  ", " ");
                    String[] split = string.split(",");

                    // Determine type
                    KillStreak.Type type = split[0].equalsIgnoreCase("mob") ? KillStreak.Type.MOB
                            : KillStreak.Type.ITEM;

                    // Load settings
                    String message = split[1].trim();

                    // Load specific settings
                    if (type == KillStreak.Type.MOB) {
                        EntityType entityType = EntityType.valueOf(split[2].toUpperCase());
                        int amount = NumberUtil.toInt(split[3]);

                        streaks.add(new KillStreak(kills, message, entityType, amount));
                    } else {
                        String item = FormatUtil.join(",", Arrays.copyOfRange(split, 2, split.length));
                        ItemStack stack = ItemUtil.readItem(item, plugin);
                        if (stack != null)
                            streaks.add(new KillStreak(kills, message, stack));
                    }
                }

                killStreaks.put(kills, streaks);
            }
        }

        this.mandatedClasses = def.getMandatedClasses();
        if (isSet(values, "mandatedClasses")) {
            this.mandatedClasses = new HashMap<>();

            for (Entry<String, Object> entry : getSection(values, "mandatedClasses").entrySet()) {
                Team team = Team.get(entry.getKey());
                if (team == null)
                    continue;

                @SuppressWarnings("unchecked")
                List<String> classes = (List<String>) entry.getValue();
                mandatedClasses.put(team, classes);
            }
        }

        // Load custom options
        loadCustomOptions(config, def);
    } catch (Throwable ex) {
        plugin.getLogHandler().log(Level.SEVERE,
                Util.getUsefulStack(ex, "loading config for \"" + type + "\""));
        return false;
    }

    plugin.getLogHandler().debug("Successfully loaded config for {0}!", type);
    return true;
}

From source file:io.stallion.dataAccess.file.FilePersisterBase.java

/**
 * Derives a Long id by hashing the file path and then taking the first 8 bytes
 * of the path.//from w ww  . j  a  v  a2  s  . co  m
 *
 * This is used if the model object doesn't have a defined id field.
 *
 * @param path
 * @return
 */
public Long makeIdFromFilePath(String path) {
    path = path.toLowerCase();
    path = path.replace(getBucketFolderPath().toLowerCase(), "");
    path = StringUtils.stripStart(path, "/");
    path = getBucket() + "-----" + path;
    // Derive a long id by hashing the file path
    byte[] bs = Arrays.copyOfRange(DigestUtils.md5(path), 0, 6);
    bs = ArrayUtils.addAll(new byte[] { 0, 0 }, bs);
    ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
    buffer.put(bs);
    buffer.flip();//need flip
    Long l = buffer.getLong();
    if (l < 0) {
        l = -l;
    }
    Log.finest("calculated id is {0}", l);
    return l;
}