Example usage for java.lang System identityHashCode

List of usage examples for java.lang System identityHashCode

Introduction

In this page you can find the example usage for java.lang System identityHashCode.

Prototype

@HotSpotIntrinsicCandidate
public static native int identityHashCode(Object x);

Source Link

Document

Returns the same hash code for the given object as would be returned by the default method hashCode(), whether or not the given object's class overrides hashCode().

Usage

From source file:org.apache.kylin.query.relnode.OLAPTableScan.java

private ColumnRowType buildColumnRowType() {
    this.alias = context.allTableScans.size() + "_" + Integer.toHexString(System.identityHashCode(this));
    TableRef tableRef = TblColRef.tableForUnknownModel(this.alias, olapTable.getSourceTable());

    List<TblColRef> columns = new ArrayList<TblColRef>();
    for (ColumnDesc sourceColumn : olapTable.getSourceColumns()) {
        TblColRef colRef = TblColRef.columnForUnknownModel(tableRef, sourceColumn);
        columns.add(colRef);//from   ww  w .  ja v a  2  s.  com
    }

    if (columns.size() != rowType.getFieldCount()) {
        throw new IllegalStateException(
                "RowType=" + rowType.getFieldCount() + ", ColumnRowType=" + columns.size());
    }
    return new ColumnRowType(columns);
}

From source file:ome.services.util.ServiceHandler.java

/**
 * public for testing purposes./*from  ww w  . j  a  va  2  s .com*/
 */
public String getResultsString(Object o, IdentityHashMap<Object, String> cache) {

    if (o == null) {
        return "null";
    }

    if (cache == null) {
        cache = new IdentityHashMap<Object, String>();
    } else {
        if (cache.containsKey(o)) {
            return (String) cache.get(o);
        }
    }

    if (o instanceof Collection) {
        int count = 0;
        StringBuilder sb = new StringBuilder(128);
        sb.append("(");
        Collection c = (Collection) o;
        for (Object obj : (c)) {
            if (count > 0) {
                sb.append(", ");
            }
            if (count > 2) {
                sb.append("... ");
                sb.append(c.size() - 3);
                sb.append(" more");
                break;
            }
            sb.append(obj);
            count++;
        }
        sb.append(")");
        return sb.toString();
    } else if (o instanceof Map) {
        Map map = (Map) o;
        int count = 0;
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        for (Object k : map.keySet()) {
            if (count > 0) {
                sb.append(", ");
            }
            if (count > 2) {
                sb.append("... ");
                sb.append(map.size() - 3);
                sb.append(" more");
                break;
            }
            sb.append(k);
            sb.append("=");
            cache.put(o, o.getClass().getName() + ":" + System.identityHashCode(o));
            sb.append(getResultsString(map.get(k), cache));
            count++;
        }
        sb.append("}");
        return sb.toString();
    } else if (o.getClass().isArray()) {
        int length = Array.getLength(o);
        if (length == 0) {
            return "[]";
        }
        StringBuilder sb = new StringBuilder(128);
        sb.append("[");
        for (int i = 0; i < length; i++) {

            if (i != 0) {
                sb.append(", ");
            }

            if (i > 2) {
                sb.append("... ");
                sb.append(i - 2);
                sb.append(" more");
                break;
            }
            sb.append(Array.get(o, i));
        }
        sb.append("]");
        return sb.toString();
    } else {
        return o.toString();
    }
}

From source file:org.apache.ranger.plugin.policyevaluator.RangerDefaultPolicyEvaluator.java

@Override
public void evaluate(RangerAccessRequest request, RangerRowFilterResult result) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> RangerDefaultPolicyEvaluator.evaluate(" + request + ", " + result + ")");
    }//  w  w  w .jav  a  2s  .c o  m

    RangerPerfTracer perf = null;

    if (RangerPerfTracer.isPerfTraceEnabled(PERF_POLICY_REQUEST_LOG)) {
        perf = RangerPerfTracer.getPerfTracer(PERF_POLICY_REQUEST_LOG,
                "RangerPolicyEvaluator.evaluate(requestHashCode="
                        + Integer.toHexString(System.identityHashCode(request)) + "," + perfTag + ")");
    }

    if (request != null && result != null && CollectionUtils.isNotEmpty(rowFilterEvaluators)) {
        if (!result.getIsAccessDetermined() || !result.getIsAuditedDetermined()) {
            RangerPolicyResourceMatcher.MatchType matchType = resourceMatcher != null
                    ? resourceMatcher.getMatchType(request.getResource(), request.getContext())
                    : RangerPolicyResourceMatcher.MatchType.NONE;

            final boolean isMatched;
            if (request.isAccessTypeAny()) {
                isMatched = matchType != RangerPolicyResourceMatcher.MatchType.NONE;
            } else if (request
                    .getResourceMatchingScope() == RangerAccessRequest.ResourceMatchingScope.SELF_OR_DESCENDANTS) {
                isMatched = matchType == RangerPolicyResourceMatcher.MatchType.SELF
                        || matchType == RangerPolicyResourceMatcher.MatchType.DESCENDANT;
            } else {
                isMatched = matchType == RangerPolicyResourceMatcher.MatchType.SELF
                        || matchType == RangerPolicyResourceMatcher.MatchType.ANCESTOR;
            }

            if (isMatched) {
                if (!result.getIsAuditedDetermined()) {
                    if (isAuditEnabled()) {
                        result.setIsAudited(true);
                        result.setAuditPolicyId(getPolicy().getId());
                    }
                }
                if (!result.getIsAccessDetermined()) {
                    if (hasMatchablePolicyItem(request)) {
                        evaluatePolicyItems(request, result);
                    }
                }
            }
        }
    }

    RangerPerfTracer.log(perf);

    if (LOG.isDebugEnabled()) {
        LOG.debug("<== RangerDefaultPolicyEvaluator.evaluate(" + request + ", " + result + ")");
    }
}

From source file:com.abstratt.mdd.core.util.MDDUtil.java

public static String toShortString(Element element) {
    return element.eClass().getName() + "@" + System.identityHashCode(element);
}

From source file:org.apache.kylin.storage.hbase.cube.v2.CubeHBaseEndpointRPC.java

@SuppressWarnings("checkstyle:methodlength")
@Override/*w  w  w . j  a  v a 2  s . co  m*/
public IGTScanner getGTScanner(final GTScanRequest scanRequest) throws IOException {

    final String toggle = BackdoorToggles.getCoprocessorBehavior() == null
            ? CoprocessorBehavior.SCAN_FILTER_AGGR_CHECKMEM.toString()
            : BackdoorToggles.getCoprocessorBehavior();

    logger.debug("New scanner for current segment {} will use {} as endpoint's behavior", cubeSeg, toggle);

    Pair<Short, Short> shardNumAndBaseShard = getShardNumAndBaseShard();
    short shardNum = shardNumAndBaseShard.getFirst();
    short cuboidBaseShard = shardNumAndBaseShard.getSecond();
    int totalShards = cubeSeg.getTotalShards();

    ByteString scanRequestByteString = null;
    ByteString rawScanByteString = null;

    // primary key (also the 0th column block) is always selected
    final ImmutableBitSet selectedColBlocks = scanRequest.getSelectedColBlocks().set(0);

    // globally shared connection, does not require close
    final HConnection conn = HBaseConnection.get(cubeSeg.getCubeInstance().getConfig().getStorageUrl());

    final List<IntList> hbaseColumnsToGTIntList = Lists.newArrayList();
    List<List<Integer>> hbaseColumnsToGT = getHBaseColumnsGTMapping(selectedColBlocks);
    for (List<Integer> list : hbaseColumnsToGT) {
        hbaseColumnsToGTIntList.add(IntList.newBuilder().addAllInts(list).build());
    }

    //TODO: raw scan can be constructed at region side to reduce traffic
    List<RawScan> rawScans = preparedHBaseScans(scanRequest.getGTScanRanges(), selectedColBlocks);
    int rawScanBufferSize = BytesSerializer.SERIALIZE_BUFFER_SIZE;
    while (true) {
        try {
            ByteBuffer rawScanBuffer = ByteBuffer.allocate(rawScanBufferSize);
            BytesUtil.writeVInt(rawScans.size(), rawScanBuffer);
            for (RawScan rs : rawScans) {
                RawScan.serializer.serialize(rs, rawScanBuffer);
            }
            rawScanBuffer.flip();
            rawScanByteString = HBaseZeroCopyByteString.wrap(rawScanBuffer.array(), rawScanBuffer.position(),
                    rawScanBuffer.limit());
            break;
        } catch (BufferOverflowException boe) {
            logger.info("Buffer size {} cannot hold the raw scans, resizing to 4 times", rawScanBufferSize);
            rawScanBufferSize *= 4;
        }
    }
    scanRequest.setGTScanRanges(Lists.<GTScanRange>newArrayList());//since raw scans are sent to coprocessor, we don't need to duplicate sending it

    int scanRequestBufferSize = BytesSerializer.SERIALIZE_BUFFER_SIZE;
    while (true) {
        try {
            ByteBuffer buffer = ByteBuffer.allocate(scanRequestBufferSize);
            GTScanRequest.serializer.serialize(scanRequest, buffer);
            buffer.flip();
            scanRequestByteString = HBaseZeroCopyByteString.wrap(buffer.array(), buffer.position(),
                    buffer.limit());
            break;
        } catch (BufferOverflowException boe) {
            logger.info("Buffer size {} cannot hold the scan request, resizing to 4 times",
                    scanRequestBufferSize);
            scanRequestBufferSize *= 4;
        }
    }

    logger.debug("Serialized scanRequestBytes {} bytes, rawScanBytesString {} bytes",
            scanRequestByteString.size(), rawScanByteString.size());

    logger.info(
            "The scan {} for segment {} is as below with {} separate raw scans, shard part of start/end key is set to 0",
            Integer.toHexString(System.identityHashCode(scanRequest)), cubeSeg, rawScans.size());
    for (RawScan rs : rawScans) {
        logScan(rs, cubeSeg.getStorageLocationIdentifier());
    }

    logger.debug("Submitting rpc to {} shards starting from shard {}, scan range count {}", shardNum,
            cuboidBaseShard, rawScans.size());

    final AtomicInteger totalScannedCount = new AtomicInteger(0);
    final ExpectedSizeIterator epResultItr = new ExpectedSizeIterator(shardNum);

    // KylinConfig: use env instance instead of CubeSegment, because KylinConfig will share among queries
    // for different cubes until redeployment of coprocessor jar.
    final KylinConfig kylinConfig = KylinConfig.getInstanceFromEnv();
    final boolean compressionResult = kylinConfig.getCompressionResult();
    final CubeVisitProtos.CubeVisitRequest.Builder builder = CubeVisitProtos.CubeVisitRequest.newBuilder();
    builder.setGtScanRequest(scanRequestByteString).setHbaseRawScan(rawScanByteString);
    for (IntList intList : hbaseColumnsToGTIntList) {
        builder.addHbaseColumnsToGT(intList);
    }
    builder.setRowkeyPreambleSize(cubeSeg.getRowKeyPreambleSize());
    builder.setBehavior(toggle);
    builder.setStartTime(System.currentTimeMillis());
    builder.setTimeout(epResultItr.getTimeout());
    builder.setKylinProperties(kylinConfig.getConfigAsString());

    for (final Pair<byte[], byte[]> epRange : getEPKeyRanges(cuboidBaseShard, shardNum, totalShards)) {
        executorService.submit(new Runnable() {
            @Override
            public void run() {

                final String logHeader = "<sub-thread for GTScanRequest "
                        + Integer.toHexString(System.identityHashCode(scanRequest)) + "> ";
                final boolean[] abnormalFinish = new boolean[1];

                try {
                    HTableInterface table = conn.getTable(cubeSeg.getStorageLocationIdentifier(),
                            HBaseConnection.getCoprocessorPool());

                    final CubeVisitRequest request = builder.build();
                    final byte[] startKey = epRange.getFirst();
                    final byte[] endKey = epRange.getSecond();

                    table.coprocessorService(CubeVisitService.class, startKey, endKey, //
                            new Batch.Call<CubeVisitService, CubeVisitResponse>() {
                                public CubeVisitResponse call(CubeVisitService rowsService) throws IOException {
                                    ServerRpcController controller = new ServerRpcController();
                                    BlockingRpcCallback<CubeVisitResponse> rpcCallback = new BlockingRpcCallback<>();
                                    rowsService.visitCube(controller, request, rpcCallback);
                                    CubeVisitResponse response = rpcCallback.get();
                                    if (controller.failedOnException()) {
                                        throw controller.getFailedOn();
                                    }
                                    return response;
                                }
                            }, new Batch.Callback<CubeVisitResponse>() {
                                @Override
                                public void update(byte[] region, byte[] row, CubeVisitResponse result) {
                                    if (region == null)
                                        return;

                                    totalScannedCount.addAndGet(result.getStats().getScannedRowCount());
                                    logger.info(logHeader + getStatsString(region, result));

                                    if (result.getStats().getNormalComplete() != 1) {
                                        abnormalFinish[0] = true;
                                        return;
                                    }
                                    try {
                                        if (compressionResult) {
                                            epResultItr
                                                    .append(CompressionUtils.decompress(HBaseZeroCopyByteString
                                                            .zeroCopyGetBytes(result.getCompressedRows())));
                                        } else {
                                            epResultItr.append(HBaseZeroCopyByteString
                                                    .zeroCopyGetBytes(result.getCompressedRows()));
                                        }
                                    } catch (IOException | DataFormatException e) {
                                        throw new RuntimeException(logHeader + "Error when decompressing", e);
                                    }
                                }
                            });

                } catch (Throwable ex) {
                    logger.error(logHeader + "Error when visiting cubes by endpoint", ex); // double log coz the query thread may already timeout
                    epResultItr.notifyCoprocException(ex);
                    return;
                }

                if (abnormalFinish[0]) {
                    Throwable ex = new RuntimeException(logHeader
                            + "The coprocessor thread stopped itself due to scan timeout, failing current query...");
                    logger.error(logHeader + "Error when visiting cubes by endpoint", ex); // double log coz the query thread may already timeout
                    epResultItr.notifyCoprocException(ex);
                    return;
                }
            }
        });
    }

    return new EndpointResultsAsGTScanner(fullGTInfo, epResultItr, scanRequest.getColumns(),
            totalScannedCount.get());
}

From source file:org.diorite.impl.command.defaults.DevCmd.java

public DevCmd() { // TODO: remove
    super("dev", Pattern.compile("(dev)(:(?<action>([a-z0-9_]*))|)", Pattern.CASE_INSENSITIVE),
            CommandPriority.LOW);/*  w w  w  .j a va  2 s.  c  om*/
    this.setDescription("Debug");
    this.setCommandExecutor((sender, command, label, matchedPattern, args) -> {
        final String action = matchedPattern.group("action");
        final IPlayer p = (IPlayer) sender;
        if (action == null) {
            p.getNetworkManager()
                    .sendPacket(new PacketPlayClientboundBlockChange(
                            args.readCoordinates(0, p.getLocation().toBlockLocation()), args.asInt(3),
                            args.asInt(4).byteValue()));
            return;
        }
        final IServerManager serverManager = DioriteCore.getInstance().getServerManager();
        final PermissionsManager mag = serverManager.getPermissionsManager();
        switch (action.toLowerCase()) {
        case "metadata": {
            final IEntity entity = p.getNearbyEntities(3, 3, 3, LookupShape.RECTANGLE).iterator().next();
            final int index = args.asInt(1);
            switch (args.asString(0)) {

            case "flag": {
                final String s = args.asString(2);
                for (final String flag : s.split(",")) {
                    entity.getMetadata().setBoolean(index, DioriteMathUtils.asInt(flag), args.asBoolean(3));
                }
                break;
            }
            case "int": {
                entity.getMetadata().setInt(index, args.asInt(2));
                break;
            }
            case "bool": {
                entity.getMetadata().setBoolean(index, args.asBoolean(2));
                break;
            }
            case "float": {
                entity.getMetadata().setFloat(index, args.asFloat(2));
                break;
            }
            case "loc": {
                entity.getMetadata().setBlockLocation(index,
                        args.readCoordinates(2, p.getLocation().toBlockLocation()));
                break;
            }
            }
            break;
        }
        case "mobname": {
            final IEntity entity = p.getNearbyEntities(3, 3, 3, LookupShape.RECTANGLE).iterator().next();
            System.out.println(args.asText());
            entity.setCustomName(
                    ChatColor.translateAlternateColorCodesInString(args.asText().replace("%n", "\n")));
            entity.setCustomNameVisible(true);
            break;
        }
        case "mob": {
            final IEntityFactory entityFactory = serverManager.getEntityFactory();
            if (args.asString(0).equalsIgnoreCase("creeper")) {
                final ICreeper creeper = entityFactory.createEntity(ICreeper.class, p.getLocation());
                creeper.getMetadata().setBoolean(ICreeper.META_KEY_CREEPER_POWERED, true);
                p.getWorld().addEntity(creeper);
            } else if (args.asString(0).equalsIgnoreCase("chickenArmy")) {
                DioriteCore.getInstance().sync(() -> {
                    for (double x = p.getX() - 10; x <= (p.getX() + 14); x += 1.5) {
                        for (double y = p.getY() - 6; y <= (p.getY() + 5); y += 1.5) {
                            for (double z = p.getZ() - 3; z <= (p.getZ() + 3); z += 1.5) {
                                final IChicken entity = entityFactory.createEntity(IChicken.class,
                                        new Location(x, y, z, p.getWorld()));
                                p.getWorld().addEntity(entity);
                            }
                        }
                    }
                }, p);
            } else if (args.asString(0).equalsIgnoreCase("zombie")) {
                final IZombie zombie = entityFactory.createEntity(IZombie.class, p.getLocation());
                zombie.setCustomName("Custom name!");
                zombie.setCustomNameVisible(true);
                //                        zombie.getMetadata().setInt(ILivingEntity.META_KEY_ARROWS_IN_BODY, args.has(1) ? args.asInt(1, 0) : 0);
                zombie.getMetadata().setInt(ILivingEntity.META_KEY_LIVING_POTION_EFFECT_COLOR,
                        args.has(1) ? Integer.parseInt(args.asString(1), 16) : 0);
                if (args.has(3)) {
                    String s = args.asString(2);
                    for (final String flag : s.split(",")) {
                        zombie.getMetadata().setBoolean(IEntity.META_KEY_ENTITY_BASIC_FLAGS,
                                DioriteMathUtils.asInt(flag), args.asBoolean(3));
                    }
                }
                zombie.setAir(-5);
                zombie.setSilent(true);
                p.getWorld().addEntity(zombie);
            } else if (args.asString(0).equalsIgnoreCase("area")) {
                final IAreaEffectCloud entity = entityFactory.createEntity(IAreaEffectCloud.class,
                        p.getLocation());
                entity.setColor(Color.AQUA);
                entity.setRadius(30);
                p.getWorld().addEntity(entity);
            } else if (args.asString(0).equalsIgnoreCase("area2")) {
                final IAreaEffectCloud entity = entityFactory.createEntity(IAreaEffectCloud.class,
                        p.getLocation());
                entity.getMetadata().setInt(IAreaEffectCloud.META_KEY_AREA_EFFECT_CLOUD_COLOR,
                        Integer.parseInt(args.asString(3), 16));
                entity.getMetadata().setFloat(IAreaEffectCloud.META_KEY_AREA_EFFECT_CLOUD_RADIUS,
                        args.asFloat(2));
                entity.getMetadata().setBoolean(IAreaEffectCloud.META_KEY_AREA_EFFECT_CLOUD_IS_POINT,
                        args.asBoolean(1));
                if (args.has(4)) {
                    Integer id = args.asInt(4);
                    if (id == null) {
                        id = Particle.getByParticleName(args.asString(4)).getParticleId();
                    }
                    entity.getMetadata().setInt(IAreaEffectCloud.META_KEY_AREA_EFFECT_CLOUD_PARTICLE_ID, id);
                }
                p.getWorld().addEntity(entity);
            } else if (args.asString(0).equalsIgnoreCase("crystal")) {
                final IEnderCrystal entity = entityFactory.createEntity(IEnderCrystal.class, p.getLocation());
                entity.getMetadata().setBoolean(IEnderCrystal.META_KEY_ENDER_CRYSTAL_SHOW_BOTTOM,
                        args.asBoolean(1));
                if (args.has(4)) {
                    entity.getMetadata().setBlockLocation(IEnderCrystal.META_KEY_ENDER_CRYSTAL_TARGET,
                            args.readCoordinates(2, p.getLocation().toBlockLocation()));
                }
                p.getWorld().addEntity(entity);
            } else {
                final IEntity entity = entityFactory.createEntity(EntityType.getByEnumName(args.asString(0)),
                        p.getLocation());
                if (entity != null) {
                    p.getWorld().addEntity(entity);
                }
            }
            break;
        }
        case "sound1": {
            p.getNetworkManager().sendPacket(
                    new PacketPlayClientboundSoundEffect(Sound.getById(args.asInt(0)), p.getLocation(), 2, 63));
            break;
        }
        case "sound2": {
            p.getNetworkManager().sendPacket(
                    new PacketPlayClientboundNamedSoundEffect(args.asString(0), p.getLocation(), 2, 63));
            break;
        }
        case "eq": {
            //                    Core
            break;
        }
        case "bookmeta": {
            final ItemStack item = new BaseItemStack(Material.WRITTEN_BOOK);
            final BookMeta meta = (BookMeta) item.getItemMeta();
            meta.setAuthor("Lel");
            meta.setPages("ugh");
            p.getInventory().add(item);
            break;
        }
        case "gib": {
            final ItemStack item = new BaseItemStack(Material.APPLE);
            item.setAmount(args.has(0) ? args.asInt(0, 1) : 1);
            final ItemMeta meta = item.getItemMeta();
            meta.setDisplayName("Diorite");
            p.getInventory().add(item);
            break;
        }
        case "potionmeta": {
            final ItemStack item = new BaseItemStack(
                    new PotionMat("POTION", 373, "minecraft:potion", 1, "POTION", (short) 8193, 5, 6) {
                    });
            final PotionMeta meta = new PotionMetaImpl(null);
            meta.addCustomEffect(new StatusEffect(StatusEffectType.INVISIBILITY, 3, 300, false, true), false);
            meta.addCustomEffect(new StatusEffect(StatusEffectType.INVISIBILITY, 3, 30000, false, true), false);
            item.setItemMeta(meta);
            p.getInventory().add(item);
            break;
        }
        case "m2": {
            final ItemMeta meta = p.getInventory().getItemInHand().getItemMeta();
            meta.setDisplayName(RandomStringUtils.randomAlphanumeric(16));
            break;
        }
        case "itemid": {
            final ItemMetaImpl meta = (ItemMetaImpl) p.getInventory().getItemInHand().getItemMeta();
            System.out.println("Meta: " + System.identityHashCode(meta) + ", tag: "
                    + (meta.getRawNbtData() == null ? "NULL"
                            : System.identityHashCode(meta.getRawNbtData()) + "")
                    + ", item: " + (!meta.getItemStack().isPresent() ? "NULL"
                            : System.identityHashCode(meta.getItemStack().get()) + ""));
            break;
        }
        case "skullmeta": {
            final ItemStack item = new BaseItemStack(SkullMat.SKULL_PLAYER);
            System.out.println(item.getItemMeta());
            final SkullMeta meta = (SkullMeta) item.getItemMeta();
            meta.setOwner(args.asString(0));
            System.out.println(meta);
            p.getInventory().add(item);
            break;
        }
        case "itemmeta": {
            final ItemStack item = new BaseItemStack(Material.STONE);
            final ItemMeta meta = item.getItemMeta();
            meta.setDisplayName("Custom name!");
            meta.setLore(Arrays.asList("North to", "gupi nup"));
            meta.addEnchant(EnchantmentType.AQUA_AFFINITY, 3, true);
            meta.addAttributeModifier(AttributeModifier.builder().setUuid(new UUID(0, 0)).setName("t")
                    .setValue(2.25D).setType(AttributeType.GENERIC_ATTACK_DAMAGE).build());
            meta.addAttributeModifier(AttributeModifier.builder().setUuid(new UUID(0, 1)).setName("t")
                    .setValue(2.25D).setType(AttributeType.GENERIC_MAX_HEALTH).build());
            p.getInventory().add(item);
            break;
        }
        case "pextest": {
            sender.setOp(false);
            mag.getPermissibleGroups(sender).forEach(g -> mag.removePermissibleFromGroup(sender, g));
            sender.sendMessage("Testing permissions: ");
            sender.sendMessage("foo.bar: " + sender.hasPermission("foo.bar")); // false
            sender.sendMessage("Your groups: " + mag.getPermissibleGroups(sender).stream()
                    .map(f -> f.getGroup().getName()).collect(Collectors.toList())); // empty
            final PermissionsGroup group = mag.createGroup("test");
            sender.sendMessage("Adding to group (" + group.getName() + "): "
                    + mag.addPermissibleToGroup(sender, group, 1)); // true
            sender.sendMessage("Your groups: " + mag.getPermissibleGroups(sender).stream()
                    .map(f -> f.getGroup().getName()).collect(Collectors.toList())); // test
            mag.setPermission(group, "foo.bar", PermissionLevel.TRUE);
            sender.sendMessage("foo.bar: " + sender.hasPermission("foo.bar")); // true
            mag.removePermissibleFromGroup(sender, "test");
            sender.sendMessage("Your groups: " + mag.getPermissibleGroups(sender).stream()
                    .map(f -> f.getGroup().getName()).collect(Collectors.toList())); // empty
            sender.sendMessage("foo.bar: " + sender.hasPermission("foo.bar")); // false
            sender.sendMessage("Adding to group (" + group.getName() + "): "
                    + mag.addPermissibleToGroup(sender, group, 1)); // true
            mag.setPermission(group, "foo.bar", PermissionLevel.OP);
            sender.sendMessage("foo.bar: " + sender.hasPermission("foo.bar")); // false
            sender.setOp(true);
            sender.sendMessage("foo.bar: " + sender.hasPermission("foo.bar")); // true
            sender.setOp(false);
            mag.setPermission(group, "foo.{$-$}", "foo.[-100--10,25-30]", PermissionLevel.TRUE); // from -100 to -10
            sender.sendMessage("foo.5: " + sender.hasPermission("foo.5")); // false
            sender.sendMessage("foo.-10: " + sender.hasPermission("foo.-10")); // true
            sender.sendMessage("foo.-25: " + sender.hasPermission("foo.-25")); // true
            sender.sendMessage("foo.25: " + sender.hasPermission("foo.25")); // true
            mag.removePermissibleFromGroup(sender, "test");
            sender.sendMessage("Your groups: " + mag.getPermissibleGroups(sender).stream()
                    .map(f -> f.getGroup().getName()).collect(Collectors.toList())); // empty
            sender.sendMessage("foo.5: " + sender.hasPermission("foo.5")); // false
            sender.sendMessage("foo.-10: " + sender.hasPermission("foo.-10")); // false
            sender.sendMessage("foo.-25: " + sender.hasPermission("foo.-25")); // false
            sender.sendMessage("foo.25: " + sender.hasPermission("foo.25")); // false
            sender.setOp(true);
            sender.sendMessage("foo.5: " + sender.hasPermission("foo.5")); // true
            sender.sendMessage("foo.-10: " + sender.hasPermission("foo.-10")); // true
            sender.sendMessage("foo.-25: " + sender.hasPermission("foo.-25")); // true
            sender.sendMessage("foo.25: " + sender.hasPermission("foo.25")); // true

            mag.addPermissibleToGroup(sender, mag.createGroup("test"), 1);
            mag.addPermissibleToGroup(sender, mag.createGroup("a1"), 2);
            mag.addPermissibleToGroup(sender, mag.createGroup("a2"), 3);
            mag.addPermissibleToGroup(sender, mag.createGroup("a3"), 4);
            sender.sendMessage("Your groups: " + mag.getPermissibleGroups(sender).stream()
                    .map(f -> f.getGroup().getName()).collect(Collectors.toList())); // test, a1, a2, a3
            mag.setPermission(mag.getGroup("test"), "test.test", PermissionLevel.FALSE);
            mag.setPermission(mag.getGroup("a3"), "test.test", PermissionLevel.TRUE);
            sender.sendMessage("test.test: " + sender.hasPermission("test.test")); // true
            mag.setPermission(sender, "test.test", PermissionLevel.NOT_OP);
            sender.sendMessage("test.test: " + sender.hasPermission("test.test")); // false
            mag.setPermission(mag.getGroup("a2"), "test.test2", PermissionLevel.FALSE);
            mag.setPermission(mag.getGroup("a1"), "test.test2", PermissionLevel.TRUE);
            sender.sendMessage("test.test2: " + sender.hasPermission("test.test2")); // false
            break;
        }
        case "pex": {
            if (sender.hasPermission(args.asString(0))) {
                sender.sendMessage("You have " + args.asString(0) + " permission!");
            } else {
                sender.sendMessage("You don't have " + args.asString(0) + " permission!");
            }
            break;
        }
        case "pexaddg": {
            final PermissionsGroup group = mag.getGroup(args.asString(0));
            if (group == null) {
                sender.sendMessage("No group, " + args.asString(0));
                return;
            }
            mag.setPermission(group, args.asString(1), args.asString(2).equalsIgnoreCase("null") ? null
                    : PermissionLevel.valueOf(args.asString(2).toUpperCase()));
            sender.sendMessage("Set permission " + args.asString(1) + ":"
                    + (args.asString(2).equalsIgnoreCase("null") ? null
                            : PermissionLevel.valueOf(args.asString(2).toUpperCase()))
                    + " to group " + group.getName());
            break;
        }
        case "pexadd": {
            mag.setPermission(sender, args.asString(0), args.asString(1).equalsIgnoreCase("null") ? null
                    : PermissionLevel.valueOf(args.asString(1).toUpperCase()));
            sender.sendMessage("Set permission " + args.asString(0) + ":"
                    + (args.asString(1).equalsIgnoreCase("null") ? null
                            : PermissionLevel.valueOf(args.asString(1).toUpperCase()))
                    + " to you");
            break;
        }
        case "pexaddu": {
            final boolean added = mag.addPermissibleToGroup(sender, args.asString(0), args.asInt(1));
            sender.sendMessage("Added you to " + args.asString(0) + " group: " + added);
            break;
        }
        case "pexreg": {
            mag.registerPermission(mag.createPermission(args.asString(0), args.asString(0),
                    PermissionLevel.valueOf(args.asString(1).toUpperCase())));
            sender.sendMessage("Register permission " + args.asString(0) + ":"
                    + PermissionLevel.valueOf(args.asString(1).toUpperCase()) + " to manager");
            break;
        }
        case "op": {
            if (p.isOp()) {
                p.setOp(false);
                sender.sendMessage("You are not op anymore...");
            } else {
                p.setOp(true);
                sender.sendMessage("You are now op!");
            }
            break;
        }
        case "pexrg": {
            final PermissionsGroup group = mag.removeGroup(args.asString(0));
            sender.sendMessage("Removed group: " + group);
            break;
        }
        case "pexcg": {
            final PermissionsGroup group = mag.createGroup(args.asString(0));
            sender.sendMessage("Created group: " + group);
            break;
        }
        case "setlocale": {
            p.setPreferedLocale((args.length() == 0) ? null : Locale.forLanguageTag(args.asText()));
            System.out.println("Done: " + p.getPreferredLocale());
            break;
        }
        case "msgr": {
            DioriteMessages.reload();
            System.out.println("Done");
            break;
        }
        case "msg": {
            p.setPreferedLocale(Locale.forLanguageTag("pl-PL"));
            DioriteMessages.broadcastMessage(args.asText(), MessageData.e("player", p),
                    MessageData.e("test", "Meeeh"));
            break;
        }
        case "tc": {
            final TextComponent tc = ComponentBuilder.start("test <r> ing").color(ChatColor.RED)
                    .event(new ClickEvent(Action.OPEN_URL, "www.diorite.org:<port>"))
                    .appendLegacy("2 costam costam 8<r> dbdjs fdd").create();
            sender.sendMessage(tc);
            System.out.println(tc.toLegacyText());
            System.out.println(ComponentSerializer.toString(tc));
            sender.sendMessage(tc.duplicate());
            System.out.println(tc.duplicate().toLegacyText());
            System.out.println(ComponentSerializer.toString(tc.duplicate()));
            break;
        }
        case "rep": {
            final TextComponent tc = ComponentBuilder.start("test <r> ing").color(ChatColor.RED)
                    .event(new ClickEvent(Action.OPEN_URL, "www.diorite.org:<port>"))
                    .appendLegacy("2 costam costam 8<r> dbdjs fdd").create();
            sender.sendMessage(tc.duplicate());
            tc.replace("<r>", ComponentBuilder.start("Replaced clickable text")
                    .event(new ClickEvent(Action.SUGGEST_COMMAND, "YeY")).create());
            tc.replace("<port>", new TextComponent("8081"));
            sender.sendMessage(tc);
            break;
        }
        case "inv": {
            ((InventoryHolder) sender).getInventory().update();
            sender.sendMessage("Inventory updated!");
            break;
        }
        case "gs": {
            p.getNetworkManager()
                    .sendPacket(new PacketPlayClientboundGameStateChange(args.asInt(0), args.asFloat(1)));
            sender.sendSimpleColoredMessage("&3Done.");
            break;
        }
        case "cb": {
            sender.sendSimpleColoredMessage(p.getLocation().toBlockLocation().getBlock().toString());
            break;
        }
        //                case "en":
        //                {
        //                    final ItemImpl item = new ItemImpl(UUID.randomUUID(), p.getCore(), IEntity.getNextEntityID(), p.getLocation().addX(3).addY(1));
        //                    item.setItemStack(new BaseItemStack(Material.TNT));
        //                    p.getWorld().addEntity(item);
        //                    break;
        //                }
        case "ep": {
            for (final IEntity e : p.getNearbyEntities(args.asDouble(0), args.asDouble(0), args.asDouble(0),
                    LookupShape.RECTANGLE)) {
                sender.sendSimpleColoredMessage("[" + e.getId() + "] " + e.getType() + ": " + e.getLocation());
            }
            break;
        }
        default: {
            sender.sendSimpleColoredMessage("&4No action...");
            break;
        }
        }
    });
}

From source file:de.innovationgate.wgpublisher.webtml.init.WebTMLEnvironmentBuilder.java

private boolean processAction(TMLContext context, HttpServletRequest request, HttpServletResponse response,
        TMLForm form, boolean ajax) {

    boolean actioncalled = false;
    // Location of Actionkey depends. When form available, then is located in form, else is URL parameter
    String actionKey = null;/*www.  jav  a2s  .  c o m*/

    try {

        if (form != null) {
            actionKey = form.getformaction();
        } else {
            actionKey = _core.getURLEncoder().decode(request.getParameter(WGPDispatcher.URLPARAM_ACTION));
        }

        // Parse the action link and call the action
        TMLActionLink actionLink;
        if (actionKey != null && !actionKey.trim().equals("")) {
            //   actions
            actionLink = TMLActionLink.read(request, actionKey, _core);
            if (actionLink == null) {
                context.addwarning("Unable to read action link: " + actionKey);
                return false;
            }

            long starttime = System.currentTimeMillis();
            TMLAction action = callAction(context, actionLink, ajax);
            long endtime = System.currentTimeMillis();

            if (_debug && action != null) {
                _core.getLog().info("Request: " + System.identityHashCode(request) + ", WebTML Action: "
                        + action.getDescription() + ", Action Mode: " + actionLink.getMode() + ", Portlet: "
                        + (context.getportlet() != null ? context.getportlet().getportletpath() + " ("
                                + context.getportlet().getportletkey() + ")" : "(none)")
                        + ", Execution time: " + (endtime - starttime));
                _response.addHeader("X-WGA-Request-DebugID", String.valueOf(System.identityHashCode(request)));
            }

            // We rebuild the session on the current context if the action was a master action
            // to be able to pick up modifications done there (F00004096) 
            if (action != null && action.isMaster()) {
                context.db().reopenSession();
            }

            //F00004242
            if (actionLink.getMode() != null
                    && actionLink.getMode().equals(TMLActionLink.MODE_AJAX_NO_PORTLET_REFRESH)) {
                // this is an ajax action call do not render content result but portletEvents, response type "text/javascript" (#00004413)
                request.setAttribute(WGACore.ATTRIB_AJAX_NOREFRESH, true);
                response.setContentType("text/javascript");
            }

            actioncalled = true;

        }
    } catch (TMLInvalidActionLinkException e) {
        if ("true".equals(System.getProperty("de.innovationgate.license.DevelopmentModeEnabled"))) {
            context.addwarning("Invalid action link calling TML action: " + e.getMessage());
        }
    } catch (TMLActionException e) {
        context.addwarning("Error calling TML action: " + e.getMessage());
    } catch (IOException e) {
        context.addwarning("Error decoding action link: " + e.getMessage());
    } catch (WGException e) {
        context.addwarning("Error calling TML action: " + e.getMessage());
    }

    return actioncalled;

}

From source file:de.ailis.midi4js.Midi4JS.java

/**
 * Returns the handle of the receiver which is connected with the
 * specified transmitter.// w  w  w.j  a v  a2 s  .  c  om
 *
 * @param transmitterHandle
 *            The handle of the transmitter.
 * @return The handle of the receiver or 0 if none.
 */
public int getTransmitterReceiver(final int transmitterHandle) {
    final Transmitter transmitter = resolveTransmitterHandle(transmitterHandle);
    final Receiver receiver = transmitter.getReceiver();
    return System.identityHashCode(receiver);
}

From source file:com.fiveamsolutions.nci.commons.data.security.AbstractUser.java

/**
 * {@inheritDoc}/*  w w  w .  j a v  a2s.com*/
 */
@Override
public int hashCode() {
    if (id == null) {
        return System.identityHashCode(this);
    }
    return id.hashCode();
}

From source file:SoftValueMap.java

void debugDump(final StringBuffer out) {
    if (out != null) {
        out.append(getClass().getName().concat("@").concat(Integer.toHexString(System.identityHashCode(this))));
        out.append(EOL);/*from  w  ww  . ja  va 2s . com*/
        out.append("size = " + m_size + ", bucket table size = " + m_buckets.length + ", load factor = "
                + m_loadFactor + EOL);
        out.append("size threshold = " + m_sizeThreshold + ", get clear frequency = "
                + m_readClearCheckFrequency + ", put clear frequency = " + m_writeClearCheckFrequency + EOL);
        out.append("get count: " + m_readAccessCount + ", put count: " + m_writeAccessCount + EOL);
    }
}