Example usage for java.nio ByteBuffer wrap

List of usage examples for java.nio ByteBuffer wrap

Introduction

In this page you can find the example usage for java.nio ByteBuffer wrap.

Prototype

public static ByteBuffer wrap(byte[] array) 

Source Link

Document

Creates a new byte buffer by wrapping the given byte array.

Usage

From source file:ffx.realspace.CCP4MapFilter.java

/**
 * {@inheritDoc}/*from  w  ww . j  av  a2 s.c om*/
 */
@Override
public Crystal getCrystal(String fileName, CompositeConfiguration properties) {
    int imapData;
    int spaceGroup = -1;
    double cellA = -1.0;
    double cellB = -1.0;
    double cellC = -1.0;
    double cellAlpha = -1.0;
    double cellBeta = -1.0;
    double cellGamma = -1.0;

    ByteOrder byteOrder = ByteOrder.nativeOrder();
    FileInputStream fileInputStream;
    DataInputStream dataInputStream;

    // first determine byte order of file versus system
    try {
        fileInputStream = new FileInputStream(fileName);
        dataInputStream = new DataInputStream(fileInputStream);

        dataInputStream.skipBytes(212);
        byte bytes[] = new byte[4];
        dataInputStream.read(bytes, 0, 4);
        ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);

        imapData = byteBuffer.order(ByteOrder.BIG_ENDIAN).getInt();
        String stampString = Integer.toHexString(imapData);

        switch (stampString.charAt(0)) {
        case '1':
        case '3':
            if (byteOrder.equals(ByteOrder.LITTLE_ENDIAN)) {
                byteOrder = ByteOrder.BIG_ENDIAN;
            }
            break;
        case '4':
            if (byteOrder.equals(ByteOrder.BIG_ENDIAN)) {
                byteOrder = ByteOrder.LITTLE_ENDIAN;
            }
            break;
        }
        fileInputStream.close();
    } catch (Exception e) {
        String message = " Fatal exception reading CCP4 map.\n";
        logger.log(Level.SEVERE, message, e);
    }

    try {
        fileInputStream = new FileInputStream(fileName);
        dataInputStream = new DataInputStream(fileInputStream);

        dataInputStream.skipBytes(40);
        byte bytes[] = new byte[80];
        dataInputStream.read(bytes, 0, 80);
        ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);

        cellA = byteBuffer.order(byteOrder).getFloat();
        cellB = byteBuffer.order(byteOrder).getFloat();
        cellC = byteBuffer.order(byteOrder).getFloat();
        cellAlpha = byteBuffer.order(byteOrder).getFloat();
        cellBeta = byteBuffer.order(byteOrder).getFloat();
        cellGamma = byteBuffer.order(byteOrder).getFloat();

        for (int i = 0; i < 3; i++) {
            byteBuffer.order(byteOrder).getInt();
        }
        for (int i = 0; i < 3; i++) {
            byteBuffer.order(byteOrder).getFloat();
        }

        spaceGroup = byteBuffer.order(byteOrder).getInt();
        fileInputStream.close();
    } catch (Exception e) {
        String message = " Fatal exception reading CCP4 map.\n";
        logger.log(Level.SEVERE, message, e);
    }

    return new Crystal(cellA, cellB, cellC, cellAlpha, cellBeta, cellGamma,
            SpaceGroup.spaceGroupNames[spaceGroup - 1]);
}

From source file:com.impetus.client.twitter.TwissandraTest.java

@Override
void createSchema() throws InvalidRequestException, SchemaDisagreementException, TException {
    KsDef ksDef = null;//w w  w  .j a v  a 2s  . c o m

    CfDef userCfDef = new CfDef();
    userCfDef.name = "USER";
    userCfDef.keyspace = keyspace;
    userCfDef.column_type = "Super";
    userCfDef.setComparator_type("UTF8Type");
    userCfDef.setDefault_validation_class("UTF8Type");

    CfDef userIndexCfDef = new CfDef();
    userIndexCfDef.name = "USER" + Constants.INDEX_TABLE_SUFFIX;
    userIndexCfDef.keyspace = keyspace;
    userIndexCfDef.setComparator_type("UTF8Type");
    userIndexCfDef.setDefault_validation_class("UTF8Type");

    CfDef prefrenceCfDef = new CfDef();
    prefrenceCfDef.name = "PREFERENCE";
    prefrenceCfDef.keyspace = keyspace;
    prefrenceCfDef.setComparator_type("UTF8Type");
    prefrenceCfDef.setDefault_validation_class("UTF8Type");
    ColumnDef columnDef = new ColumnDef(ByteBuffer.wrap("WEBSITE_THEME".getBytes()), "UTF8Type");
    columnDef.index_type = IndexType.KEYS;
    ColumnDef columnDef3 = new ColumnDef(ByteBuffer.wrap("PRIVACY_LEVEL".getBytes()), "UTF8Type");
    columnDef3.index_type = IndexType.KEYS;
    prefrenceCfDef.addToColumn_metadata(columnDef);
    prefrenceCfDef.addToColumn_metadata(columnDef3);

    CfDef externalLinkCfDef = new CfDef();
    externalLinkCfDef.name = "EXTERNAL_LINK";
    externalLinkCfDef.keyspace = keyspace;
    externalLinkCfDef.setComparator_type("UTF8Type");
    externalLinkCfDef.setDefault_validation_class("UTF8Type");
    ColumnDef columnDef1 = new ColumnDef(ByteBuffer.wrap("LINK_TYPE".getBytes()), "UTF8Type");
    columnDef1.index_type = IndexType.KEYS;
    ColumnDef columnDef2 = new ColumnDef(ByteBuffer.wrap("LINK_ADDRESS".getBytes()), "UTF8Type");
    columnDef2.index_type = IndexType.KEYS;
    ColumnDef columnDef4 = new ColumnDef(ByteBuffer.wrap("USER_ID".getBytes()), "UTF8Type");
    columnDef4.index_type = IndexType.KEYS;
    externalLinkCfDef.addToColumn_metadata(columnDef1);
    externalLinkCfDef.addToColumn_metadata(columnDef2);
    externalLinkCfDef.addToColumn_metadata(columnDef4);

    List<CfDef> cfDefs = new ArrayList<CfDef>();
    cfDefs.add(userCfDef);
    cfDefs.add(userIndexCfDef);
    cfDefs.add(prefrenceCfDef);
    cfDefs.add(externalLinkCfDef);
    try {
        ksDef = CassandraCli.client.describe_keyspace(keyspace);
        CassandraCli.client.set_keyspace(keyspace);
        List<CfDef> cfDefn = ksDef.getCf_defs();

        for (CfDef cfDef1 : cfDefn) {

            if (cfDef1.getName().equalsIgnoreCase("USER")) {
                CassandraCli.client.system_drop_column_family("USER");
            }
            if (cfDef1.getName().equalsIgnoreCase("USER" + Constants.INDEX_TABLE_SUFFIX)) {
                CassandraCli.client.system_drop_column_family("USER" + Constants.INDEX_TABLE_SUFFIX);
            }
            if (cfDef1.getName().equalsIgnoreCase("PREFERENCE")) {
                CassandraCli.client.system_drop_column_family("PREFERENCE");
            }
            if (cfDef1.getName().equalsIgnoreCase("EXTERNAL_LINK")) {
                CassandraCli.client.system_drop_column_family("EXTERNAL_LINK");
            }
        }
        CassandraCli.client.system_add_column_family(userCfDef);
        CassandraCli.client.system_add_column_family(userIndexCfDef);
        CassandraCli.client.system_add_column_family(externalLinkCfDef);
        CassandraCli.client.system_add_column_family(prefrenceCfDef);
    } catch (NotFoundException e) {
        ksDef = new KsDef(keyspace, SimpleStrategy.class.getSimpleName(), cfDefs);

        // Set replication factor
        if (ksDef.strategy_options == null) {
            ksDef.strategy_options = new LinkedHashMap<String, String>();
        }
        // Set replication factor, the value MUST be an integer
        ksDef.strategy_options.put("replication_factor", "1");

        CassandraCli.client.system_add_keyspace(ksDef);
    } catch (InvalidRequestException e) {
        log.error(e.getMessage());
    } catch (TException e) {
        log.error(e.getMessage());
    }
}

From source file:com.icloud.framework.core.util.FBUtilities.java

public static ByteBuffer toByteBuffer(int i) {
    byte[] bytes = new byte[4];
    bytes[0] = (byte) ((i >>> 24) & 0xFF);
    bytes[1] = (byte) ((i >>> 16) & 0xFF);
    bytes[2] = (byte) ((i >>> 8) & 0xFF);
    bytes[3] = (byte) (i & 0xFF);
    return ByteBuffer.wrap(bytes);
}

From source file:internal.coprocessor.NonAggregatingRegionObserver.java

/**
 * Builds the regionIndex by going through all the store files for each region and creating a reader for it that can
 * later be used to read the bloom filters, on demand.
 *///w w w .  ja v  a2 s  .c  om
@VisibleForTesting
public static NavigableMap<ByteBuffer, ListMultimap<ByteBuffer, BloomFilter>> buildIndex(String tableName,
        Configuration conf, FileSystem fileSystem, Path tableBasePath) throws IOException {
    ImmutableSortedMap.Builder<ByteBuffer, ListMultimap<ByteBuffer, BloomFilter>> indexBuilder = ImmutableSortedMap
            .naturalOrder();
    try {
        HTable table = new HTable(conf, tableName);
        NavigableMap<HRegionInfo, ServerName> regions = table.getRegionLocations();
        Collection<HColumnDescriptor> families = table.getTableDescriptor().getFamilies();
        table.close();
        LOG.info("Building RegionIndex [Table: " + tableName + " Base Path: " + tableBasePath.toString() + "]");
        for (HRegionInfo region : regions.keySet()) {
            ImmutableListMultimap.Builder<ByteBuffer, BloomFilter> familiesAndStoreFiles = ImmutableListMultimap
                    .builder();
            for (HColumnDescriptor family : families) {
                Path path = new Path(tableBasePath,
                        region.getEncodedName() + Path.SEPARATOR + family.getNameAsString());
                FileStatus[] storeFilesStatuses = fileSystem.listStatus(path);
                for (FileStatus status : storeFilesStatuses) {
                    LOG.info("Processing Store File: " + status.getPath().toString() + " Column Family: "
                            + family.getNameAsString() + " for Region: " + region.getRegionNameAsString());
                    // maybe increased the cache for this reader since it's be only reading blooms?
                    HFile.Reader reader = HFile.createReader(fileSystem, status.getPath(),
                            new CacheConfig(conf));
                    familiesAndStoreFiles.put(ByteBuffer.wrap(family.getName()),
                            BloomFilterFactory.createFromMeta(reader.getGeneralBloomFilterMetadata(), reader));
                }
            }
            indexBuilder.put(ByteBuffer.wrap(region.getStartKey()), familiesAndStoreFiles.build());
        }
        return indexBuilder.build();
    } catch (Exception e) {
        LOG.error("Could not load regionIndex, BloomFilterSemiJoinFilter will not work.", e);
    }
    return null;
}

From source file:com.sm.store.Utils.java

public static void addOne(Value value) {
    ByteBuffer buf = ByteBuffer.wrap((byte[]) value.getData());
    int k = buf.getInt() + 1;
    byte[] data = putInt(k);
    value.setData(data);/*w  w  w  .  j  a v a  2 s. c  om*/
    value.setVersion(value.getVersion() + 1);
}

From source file:me.footlights.core.crypto.Fingerprint.java

public boolean matches(byte[] b) {
    return matches(ByteBuffer.wrap(b));
}

From source file:oz.hadoop.yarn.api.core.LocalApplicationLaunchTests.java

@Test(timeout = 60000)
public void validateLongLivedJavaContainerLaunch() throws Exception {
    YarnApplication<DataProcessor> yarnApplication = YarnAssembly
            .forApplicationContainer(SimpleRandomDelayContainer.class).containerCount(2).memory(512)
            .withApplicationMaster().maxAttempts(2).priority(2).build("sample-yarn-application");

    DataProcessor dataProcessor = yarnApplication.launch();
    assertEquals(2, dataProcessor.containers());

    for (int i = 0; i < 5; i++) {
        for (int j = 0; j < dataProcessor.containers(); j++) {
            dataProcessor.process(ByteBuffer.wrap(("Hello Yarn!-" + i).getBytes()));
        }//from  w  w w .  java  2s. c  om
    }
    assertTrue(yarnApplication.isRunning());
    yarnApplication.shutDown();
    assertFalse(yarnApplication.isRunning());
}

From source file:com.networknt.light.server.handler.RestHandler.java

@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    if (exchange.isInIoThread()) {
        exchange.dispatch(this);
        return;// w w  w .  j  av  a 2 s  .c om
    }

    exchange.startBlocking();
    // check if it is get or post
    String json = null;
    Map<String, Object> jsonMap = null;
    if (Methods.GET.equals(exchange.getRequestMethod())) {
        Map params = exchange.getQueryParameters();
        String cmd = ((Deque<String>) params.get("cmd")).getFirst();
        json = URLDecoder.decode(cmd, "UTF8");
    } else if (Methods.POST.equals(exchange.getRequestMethod())) {
        json = new Scanner(exchange.getInputStream(), "UTF-8").useDelimiter("\\A").next();
    } else {
        logger.error("Invalid Request Method");
        exchange.setResponseCode(400);
        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
        exchange.getResponseSender().send((ByteBuffer.wrap("Invalid Request Method".getBytes("utf-8"))));
        return;
    }
    //logger.debug("json = {}", json);

    // convert json string to map here. It it cannot be converted, then it is invalid command.
    try {
        jsonMap = ServiceLocator.getInstance().getMapper().readValue(json,
                new TypeReference<HashMap<String, Object>>() {
                });
    } catch (Exception e) {
        exchange.setResponseCode(400);
        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
        exchange.getResponseSender().send((ByteBuffer.wrap("invalid_command".getBytes("utf-8"))));
        return;
    }

    // TODO validate with json schema to make sure the input json is valid. return an error message otherwise.
    // you need to get the schema from db again for the one sent from browser might be modified.
    String cmdRuleClass = Util.getCommandRuleId(jsonMap);
    boolean readOnly = (boolean) jsonMap.get("readOnly");
    if (!readOnly) {
        JsonSchema schema = AbstractValidationRule.getSchema(cmdRuleClass);
        if (schema != null) {
            // validate only if schema is not null.
            JsonNode jsonNode = mapper.valueToTree(jsonMap);
            ProcessingReport report = schema.validate(jsonNode.get("data"));
            logger.debug("report" + report);
            if (!report.isSuccess()) {
                exchange.setResponseCode(400);
                exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
                JsonNode messages = ((ListProcessingReport) report).asJson();
                exchange.getResponseSender().send((ByteBuffer.wrap(messages.toString().getBytes("utf-8"))));
                return;
            }
        }
    }

    HeaderMap headerMap = exchange.getRequestHeaders();
    Map<String, Object> payload = null;
    try {
        payload = getTokenPayload(headerMap);
    } catch (IllegalStateException e) {
        //e.printStackTrace();
        String msg = e.getMessage();
        if (msg != null && msg.startsWith(JwtUtil.TOKEN_EXPIRED_MESSAGE)) {
            // return 401 status and let client to refresh the token.
            exchange.setResponseCode(401);
            exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
            exchange.getResponseSender().send((ByteBuffer.wrap("token_expired".getBytes("utf-8"))));
            return;
        } else {
            // invalid token, return 401 status and let client to discard the token.
            exchange.setResponseCode(401);
            exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
            exchange.getResponseSender().send((ByteBuffer.wrap("invalid_token".getBytes("utf-8"))));
            return;
        }
    }

    GetAccessRule rule = new GetAccessRule();
    Map<String, Object> access = rule.getAccessByRuleClass(cmdRuleClass);
    if (access != null) {
        // authorization rule available, check it.
        String accessLevel = (String) access.get("accessLevel");
        switch (accessLevel) {
        case "A":
            // Access by anyone.
            break;
        case "N":
            // Not accessible
            exchange.setResponseCode(400);
            exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
            exchange.getResponseSender().send((ByteBuffer.wrap("Not accessible".getBytes("utf-8"))));
            return;
        case "C":
            // client id is in the jwt token like userId and roles.
            if (payload == null) {
                exchange.setResponseCode(401);
                exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
                exchange.getResponseSender().send((ByteBuffer.wrap("Login is required".getBytes("utf-8"))));
                return;
            } else {
                Map<String, Object> user = (Map<String, Object>) payload.get("user");
                String clientId = (String) user.get("clientId");
                List<String> clients = (List) access.get("clients");
                if (!clients.contains(clientId)) {
                    exchange.setResponseCode(403);
                    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
                    exchange.getResponseSender()
                            .send((ByteBuffer.wrap("Client permission denied".getBytes("utf-8"))));
                    return;
                }
            }
            break;
        case "R":
            // role only
            if (payload == null) {
                exchange.setResponseCode(401);
                exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
                exchange.getResponseSender().send((ByteBuffer.wrap("Login is required".getBytes("utf-8"))));
                return;
            } else {
                Map<String, Object> user = (Map<String, Object>) payload.get("user");
                List userRoles = (List) user.get("roles");
                List<String> accessRoles = (List) access.get("roles");
                boolean found = false;
                for (String role : accessRoles) {
                    if (userRoles.contains(role)) {
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    exchange.setResponseCode(403);
                    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
                    exchange.getResponseSender()
                            .send((ByteBuffer.wrap("Role permission denied".getBytes("utf-8"))));
                    return;
                }
            }
            break;
        case "U":
            //user only
            if (payload == null) {
                exchange.setResponseCode(401);
                exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
                exchange.getResponseSender().send((ByteBuffer.wrap("Login is required".getBytes("utf-8"))));
                return;
            } else {
                Map<String, Object> user = (Map<String, Object>) payload.get("user");
                String userId = (String) user.get("userId");
                List<String> users = (List) access.get("users");
                if (!users.contains(userId)) {
                    exchange.setResponseCode(403);
                    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
                    exchange.getResponseSender()
                            .send((ByteBuffer.wrap("User permission denied".getBytes("utf-8"))));
                    return;
                }
            }
            break;
        case "CR":
            // client and role
            if (payload == null) {
                exchange.setResponseCode(401);
                exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
                exchange.getResponseSender().send((ByteBuffer.wrap("Login is required".getBytes("utf-8"))));
                return;
            } else {
                Map<String, Object> user = (Map<String, Object>) payload.get("user");
                String clientId = (String) user.get("clientId");
                List<String> clients = (List) access.get("clients");
                if (!clients.contains(clientId)) {
                    exchange.setResponseCode(403);
                    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
                    exchange.getResponseSender()
                            .send((ByteBuffer.wrap("Client permission denied".getBytes("utf-8"))));
                    return;
                }
                // client is ok, check roles
                List userRoles = (List) user.get("roles");
                List<String> accessRoles = (List) access.get("roles");
                boolean found = false;
                for (String role : accessRoles) {
                    if (userRoles.contains(role)) {
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    exchange.setResponseCode(403);
                    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
                    exchange.getResponseSender()
                            .send((ByteBuffer.wrap("Role permission denied".getBytes("utf-8"))));
                    return;
                }
            }
            break;
        case "CU":
            // client and user
            if (payload == null) {
                exchange.setResponseCode(401);
                exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
                exchange.getResponseSender().send((ByteBuffer.wrap("Login is required".getBytes("utf-8"))));
                return;
            } else {
                Map<String, Object> user = (Map<String, Object>) payload.get("user");
                String clientId = (String) user.get("clientId");
                List<String> clients = (List) access.get("clients");
                if (!clients.contains(clientId)) {
                    exchange.setResponseCode(403);
                    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
                    exchange.getResponseSender()
                            .send((ByteBuffer.wrap("Client permission denied".getBytes("utf-8"))));
                    return;
                }
                // client is ok, check user
                String userId = (String) user.get("userId");
                List<String> users = (List) access.get("users");
                if (!users.contains(userId)) {
                    exchange.setResponseCode(403);
                    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
                    exchange.getResponseSender()
                            .send((ByteBuffer.wrap("User permission denied".getBytes("utf-8"))));
                    return;
                }
            }
            break;
        case "RU":
            // role and user
            if (payload == null) {
                exchange.setResponseCode(401);
                exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
                exchange.getResponseSender().send((ByteBuffer.wrap("Login is required".getBytes("utf-8"))));
                return;
            } else {
                Map<String, Object> user = (Map<String, Object>) payload.get("user");
                List userRoles = (List) user.get("roles");
                List<String> accessRoles = (List) access.get("roles");
                boolean found = false;
                for (String role : accessRoles) {
                    if (userRoles.contains(role)) {
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    exchange.setResponseCode(403);
                    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
                    exchange.getResponseSender()
                            .send((ByteBuffer.wrap("Role permission denied".getBytes("utf-8"))));
                    return;
                }
                // role is OK, now check userId
                String userId = (String) user.get("userId");
                List<String> users = (List) access.get("users");
                if (!users.contains(userId)) {
                    exchange.setResponseCode(403);
                    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
                    exchange.getResponseSender()
                            .send((ByteBuffer.wrap("User permission denied".getBytes("utf-8"))));
                    return;
                }
            }
            break;
        case "CRU":
            // client, role and user
            if (payload == null) {
                exchange.setResponseCode(401);
                exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
                exchange.getResponseSender().send((ByteBuffer.wrap("Login is required".getBytes("utf-8"))));
                return;
            } else {
                Map<String, Object> user = (Map<String, Object>) payload.get("user");
                String clientId = (String) user.get("clientId");
                List<String> clients = (List) access.get("clients");
                if (!clients.contains(clientId)) {
                    exchange.setResponseCode(403);
                    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
                    exchange.getResponseSender()
                            .send((ByteBuffer.wrap("Client permission denied".getBytes("utf-8"))));
                    return;
                }
                // client is ok, check roles
                List userRoles = (List) user.get("roles");
                List<String> accessRoles = (List) access.get("roles");
                boolean found = false;
                for (String role : accessRoles) {
                    if (userRoles.contains(role)) {
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    exchange.setResponseCode(403);
                    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
                    exchange.getResponseSender()
                            .send((ByteBuffer.wrap("Role permission denied".getBytes("utf-8"))));
                    return;
                }
                // role is OK, now check userId
                String userId = (String) user.get("userId");
                List<String> users = (List) access.get("users");
                if (!users.contains(userId)) {
                    exchange.setResponseCode(403);
                    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
                    exchange.getResponseSender()
                            .send((ByteBuffer.wrap("User permission denied".getBytes("utf-8"))));
                    return;
                }
            }
            break;
        default:
            logger.error("Invalid Access Level: " + accessLevel);
        }
    }

    if (payload != null) {
        // put payload as part of the map
        jsonMap.put("payload", payload);
    }

    // TODO should I remove the port number here?
    // inject host into the data in command if there is no host in the json map.
    // that means the rules to be accessed are common and host should be part of the data.
    // if there is host in the command, then the corresponding rule should be host specific
    // and table(s) to be accessed should be host specific as well.
    if (jsonMap.get("host") == null) {
        String host = headerMap.getFirst("host");
        if (host.indexOf(':') != -1) {
            host = host.substring(0, host.indexOf(":"));
        }
        Map<String, Object> data = (Map<String, Object>) jsonMap.get("data");
        if (data == null) {
            data = new HashMap<String, Object>();
            jsonMap.put("data", data);
            data.put("host", host);
        } else {
            // do not replace host as it might be owner doing something for one host from another.
            if (data.get("host") == null) {
                data.put("host", host);
            }
        }
    }

    // inject ip address into the command here and saved as part of event in order to  identify
    // users that are not logged in.
    jsonMap.put("ipAddress", getIpAddress(exchange));

    // TODO Apply request transform rules. For example routing here for A/B testing.

    GetTransformRequestRule transformRule = new GetTransformRequestRule();
    List<Map<String, Object>> transforms = transformRule.getTransformRequest(cmdRuleClass);
    for (Map<String, Object> transform : transforms) {
        jsonMap.put("transformData", transform.get("transformData"));
        RuleEngine.getInstance().executeRule((String) transform.get("transformRule"), jsonMap);
    }

    // two types of rules (Command Rule and Event Rule)
    // Command Rule is responsible for validation and return result to client and enrich the command to event that
    // can be replayed at anytime without side effect.Once this is done, return to client. Also, it there are any
    // calls to the outside system, they should be performed here in order to avoid side effects.
    //
    // Event rule is responsible to update domain model based on the event enriched by Command Rule.

    if (readOnly) {
        // get data from memory and return it, it call a command rule to get the data and result will be in the jsonMap as "result" key
        // call the right rule to execute the command, return error code and message if validation fails.
        RuleEngine.getInstance().executeRule(Util.getCommandRuleId(jsonMap), jsonMap);
    } else {
        // this is a update command or impacting to external system.
        // TODO validate version number in itself and dependencies to make sure the event is valid. Reject it back if not.
        // TODO This is the command that need to be executed, and it should be done only once to eliminate side effect.
        // Once this is done, the jsonMap is enriched so that the event is created and can be replayed.
        // It is very possible that something needs to be returned, put it in "result" key in jsonMap.
        boolean valid = RuleEngine.getInstance().executeRule(Util.getCommandRuleId(jsonMap), jsonMap);
        if (valid) {
            // persist event into event store.
            Map<String, Object> eventMap = (Map<String, Object>) jsonMap.get("eventMap");
            DbService.persistEvent(eventMap);

            // Publish the event to subscribers here to update snapshot and cache and etags.

            // This is the async call to update domain model after the fact. Nothing should be returned from here.
            // Basically, this is to apply event generated by the Command Rule
            RuleEngine.getInstance().executeRuleAsync(Util.getEventRuleId(eventMap), eventMap);
        }
    }
    // orientdb most likely return ODocument and ODocument collection, convert to json string by rules
    String result = null;
    Integer responseCode = (Integer) jsonMap.get("responseCode");
    if (responseCode != null) {
        // there is an error
        exchange.setResponseCode(responseCode);
        result = (String) jsonMap.get("error");
        logger.debug("response error: {}", result);
        // TODO should I log the response error here or in the response interceptor?
        // do I have all the info here?

    } else {
        //  no error
        result = (String) jsonMap.get("result");

        // TODO apply response transform rule. Not supported currently yet.

        logger.debug("response success: {} ", result);
    }
    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8);
    if (result != null) {
        exchange.getResponseSender().send(ByteBuffer.wrap(result.getBytes("utf-8")));
    }
}

From source file:com.codeabovelab.dm.common.security.token.SignedTokenServiceBackend.java

@Override
public TokenData getToken(String tokenString) {
    final String key = unwrapToken(tokenString);
    if (key.isEmpty()) {
        return null;
    }/*from ww w .j a  v a 2s  .com*/
    byte[] decodedKey = base32.decode(key);
    byte[] currentSignature;
    final long creationTime;
    byte[] random;
    byte[] payload;
    {
        byte[] content;
        {
            ByteBuffer buffer = ByteBuffer.wrap(decodedKey);
            content = restoreArray(buffer);
            currentSignature = restoreArray(buffer);
        }

        ByteBuffer contentBuffer = ByteBuffer.wrap(content);
        creationTime = contentBuffer.getLong();
        random = restoreArray(contentBuffer);
        // we need to skip secret
        restoreArray(contentBuffer);
        payload = restoreArray(contentBuffer);
    }

    final byte[] serverSecret = computeServerSecretApplicableAt(creationTime);

    // Verification
    byte[] expectedSign = sign(contentPack(creationTime, random, serverSecret, payload));
    Assert.isTrue(Arrays.equals(expectedSign, currentSignature), "Key verification failure");

    String[] unpack = unpack(Utf8.decode(payload));
    return new TokenDataImpl(creationTime, TokenUtils.getKeyWithTypeAndToken(TYPE, key), unpack[0], unpack[1]);
}

From source file:com.spectralogic.ds3client.helpers.FileObjectPutter_Test.java

@Test
public void testRelativeSymlink() throws IOException, URISyntaxException {
    assumeFalse(Platform.isWindows());/* w ww  . j  a  v  a 2  s  .  com*/
    final Path tempDir = Files.createTempDirectory("ds3_file_object_rel_test_");
    final Path tempPath = Files.createTempFile(tempDir, "temp_", ".txt");

    try {
        try (final SeekableByteChannel channel = Files.newByteChannel(tempPath, StandardOpenOption.CREATE,
                StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) {
            channel.write(ByteBuffer.wrap(testData));
        }

        final Path symLinkPath = tempDir.resolve("sym_" + tempPath.getFileName().toString());
        final Path relPath = Paths.get("..", getParentDir(tempPath), tempPath.getFileName().toString());

        LOG.info("Creating symlink from " + symLinkPath.toString() + " to " + relPath.toString());

        Files.createSymbolicLink(symLinkPath, relPath);
        getFileWithPutter(tempDir, symLinkPath);

    } finally {
        Files.deleteIfExists(tempPath);
        Files.deleteIfExists(tempDir);
    }
}