Example usage for java.lang Thread setName

List of usage examples for java.lang Thread setName

Introduction

In this page you can find the example usage for java.lang Thread setName.

Prototype

public final synchronized void setName(String name) 

Source Link

Document

Changes the name of this thread to be equal to the argument name .

Usage

From source file:org.dasein.cloud.aws.compute.EC2Instance.java

private @Nonnull List<VirtualMachine> runInstances(@Nonnull VMLaunchOptions cfg, @Nonnegative int instanceCount)
        throws CloudException, InternalException {
    List<VirtualMachine> servers = new ArrayList<VirtualMachine>(); // instance cache
    List<String> instanceIds = new ArrayList<String>(); // instanceId cache

    ProviderContext ctx = getProvider().getContext();
    if (ctx == null) {
        throw new CloudException("No context was established for this request");
    }/*w ww. j  av  a 2 s.  c  o m*/
    MachineImage img = null;
    final ComputeServices computeServices = getProvider().getComputeServices();
    if (computeServices != null) {
        img = computeServices.getImageSupport().getImage(cfg.getMachineImageId());
    }

    if (img == null) {
        throw new AWSResourceNotFoundException("No such machine image: " + cfg.getMachineImageId());
    }
    Map<String, String> parameters = getProvider().getStandardParameters(getProvider().getContext(),
            EC2Method.RUN_INSTANCES);
    String ramdiskImage = (String) cfg.getMetaData().get("ramdiskImageId"),
            kernelImage = (String) cfg.getMetaData().get("kernelImageId");
    EC2Method method;
    NodeList blocks;
    Document doc;

    parameters.put("ImageId", cfg.getMachineImageId());
    parameters.put("MinCount", String.valueOf(instanceCount));
    parameters.put("MaxCount", String.valueOf(instanceCount));
    parameters.put("InstanceType", cfg.getStandardProductId());
    AWSCloud.addValueIfNotNull(parameters, "ramdiskId", ramdiskImage);
    AWSCloud.addValueIfNotNull(parameters, "kernelId", kernelImage);
    AWSCloud.addValueIfNotNull(parameters, "IamInstanceProfile.Arn", cfg.getRoleId());
    if (cfg.getUserData() != null) {
        try {
            parameters.put("UserData", Base64.encodeBase64String(cfg.getUserData().getBytes("utf-8")));
        } catch (UnsupportedEncodingException e) {
            throw new InternalException(e);
        }
    }
    if (cfg.isPreventApiTermination()) {
        parameters.put("DisableApiTermination", "true");
    }
    if (cfg.getDataCenterId() != null) {
        parameters.put("Placement.AvailabilityZone", cfg.getDataCenterId());
    } else if (cfg.getVolumes().length > 0) {
        for (VolumeAttachment a : cfg.getVolumes()) {
            if (a.volumeToCreate != null) {
                String dc = a.volumeToCreate.getDataCenterId();
                if (dc != null) {
                    cfg.inDataCenter(dc);
                    break;
                }
            }
        }
    }
    AWSCloud.addValueIfNotNull(parameters, "KeyName", cfg.getBootstrapKey());

    if (getProvider().getEC2Provider().isAWS()) {
        parameters.put("Monitoring.Enabled", String.valueOf(cfg.isExtendedAnalytics()));
    }
    if (cfg.isIoOptimized()) {
        parameters.put("EbsOptimized", "true");
    }
    AWSCloud.addValueIfNotNull(parameters, "Placement.GroupName", cfg.getAffinityGroupId());

    final ArrayList<VolumeAttachment> existingVolumes = new ArrayList<VolumeAttachment>();
    TreeSet<String> deviceIds = new TreeSet<String>();
    if (cfg.getVolumes().length > 0) {
        Iterable<String> possibles = getProvider().getComputeServices().getVolumeSupport()
                .listPossibleDeviceIds(img.getPlatform());
        int i = 1;

        for (VolumeAttachment a : cfg.getVolumes()) {
            if (a.deviceId != null) {
                deviceIds.add(a.deviceId);
            } else if (a.volumeToCreate != null && a.volumeToCreate.getDeviceId() != null) {
                deviceIds.add(a.volumeToCreate.getDeviceId());
                a.deviceId = a.volumeToCreate.getDeviceId();
            }
        }
        for (VolumeAttachment a : cfg.getVolumes()) {
            if (a.deviceId == null) {
                for (String id : possibles) {
                    if (!deviceIds.contains(id)) {
                        a.deviceId = id;
                        deviceIds.add(id);
                    }
                }
                if (a.deviceId == null) {
                    throw new InternalException("Unable to identify a device ID for volume");
                }
            }
            if (a.existingVolumeId == null) {
                parameters.put("BlockDeviceMapping." + i + ".DeviceName", a.deviceId);

                VolumeProduct prd = getProvider().getComputeServices().getVolumeSupport()
                        .getVolumeProduct(a.volumeToCreate.getVolumeProductId());
                parameters.put("BlockDeviceMapping." + i + ".Ebs.VolumeType", prd.getProviderProductId());

                if (a.volumeToCreate.getIops() > 0) {
                    parameters.put("BlockDeviceMapping." + i + ".Ebs.Iops",
                            String.valueOf(a.volumeToCreate.getIops()));
                }

                if (a.volumeToCreate.getSnapshotId() != null) {
                    parameters.put("BlockDeviceMapping." + i + ".Ebs.SnapshotId",
                            a.volumeToCreate.getSnapshotId());
                } else {
                    parameters.put("BlockDeviceMapping." + i + ".Ebs.VolumeSize",
                            String.valueOf(a.volumeToCreate.getVolumeSize().getQuantity().intValue()));
                }
                i++;
            } else {
                existingVolumes.add(a);
            }
        }
    }
    if (cfg.getSubnetId() == null) {
        AWSCloud.addIndexedParameters(parameters, "SecurityGroupId.", cfg.getFirewallIds());
    } else if (cfg.getNetworkInterfaces() != null && cfg.getNetworkInterfaces().length > 0) {
        VMLaunchOptions.NICConfig[] nics = cfg.getNetworkInterfaces();
        int i = 1;

        for (VMLaunchOptions.NICConfig c : nics) {
            parameters.put("NetworkInterface." + i + ".DeviceIndex", String.valueOf(i));
            // this only applies for the first NIC
            if (i == 1) {
                parameters.put("NetworkInterface.1.AssociatePublicIpAddress",
                        String.valueOf(cfg.isAssociatePublicIpAddress()));
            }
            if (c.nicId == null) {
                parameters.put("NetworkInterface." + i + ".SubnetId", c.nicToCreate.getSubnetId());
                parameters.put("NetworkInterface." + i + ".Description", c.nicToCreate.getDescription());
                AWSCloud.addValueIfNotNull(parameters, "NetworkInterface." + i + ".PrivateIpAddress",
                        c.nicToCreate.getIpAddress());
                AWSCloud.addIndexedParameters(parameters, "NetworkInterface." + i + ".SecurityGroupId.",
                        c.nicToCreate.getFirewallIds());
            } else {
                parameters.put("NetworkInterface." + i + ".NetworkInterfaceId", c.nicId);
            }
            i++;
        }
    } else {
        parameters.put("NetworkInterface.1.DeviceIndex", "0");
        parameters.put("NetworkInterface.1.SubnetId", cfg.getSubnetId());
        parameters.put("NetworkInterface.1.AssociatePublicIpAddress",
                String.valueOf(cfg.isAssociatePublicIpAddress()));
        AWSCloud.addValueIfNotNull(parameters, "NetworkInterface.1.PrivateIpAddress", cfg.getPrivateIp());
        AWSCloud.addIndexedParameters(parameters, "NetworkInterface.1.SecurityGroupId.", cfg.getFirewallIds());
    }

    // Send request to AWS
    method = new EC2Method(getProvider(), parameters);
    try {
        doc = method.invoke();
    } catch (EC2Exception e) {
        String code = e.getCode();

        if (code != null && code.equals("InsufficientInstanceCapacity")) {
            return servers;
        }
        logger.error(e.getSummary());
        throw new CloudException(e);
    }
    blocks = doc.getElementsByTagName("instancesSet");

    for (int i = 0; i < blocks.getLength(); i++) {
        NodeList instances = blocks.item(i).getChildNodes();

        for (int j = 0; j < instances.getLength(); j++) {
            Node instance = instances.item(j);

            if (instance.getNodeName().equals("item")) {
                VirtualMachine server = toVirtualMachine(ctx, instance,
                        new ArrayList<IpAddress>() /* can't be an elastic IP */);
                if (server != null) {
                    servers.add(server);
                    instanceIds.add(server.getProviderVirtualMachineId());
                }
            }
        }
    }

    // Wait for EC2 to figure out the server exists
    List<VirtualMachine> serversCopy = describeInstances(instanceIds.toArray(new String[instanceIds.size()]));
    long timeout = System.currentTimeMillis() + CalendarWrapper.MINUTE;
    while (timeout > System.currentTimeMillis() && serversCopy.size() < servers.size()) {
        try {
            Thread.sleep(5000L);
        } catch (InterruptedException ignore) {
        }
        try {
            serversCopy = describeInstances(instanceIds.toArray(new String[instanceIds.size()]));
        } catch (Throwable ignore) {
        }
    }

    // FIXME: not clear what is to be done if time is out but `serversCopy` is still less than `servers`

    // Set all instances their tags
    List<Tag> tags = new ArrayList<Tag>();
    Map<String, Object> meta = cfg.getMetaData();
    for (Map.Entry<String, Object> entry : meta.entrySet()) {
        if (entry.getKey().equalsIgnoreCase("name") || entry.getKey().equalsIgnoreCase("description")) {
            continue;
        }
        // Tag value can be null, make sure we are careful
        tags.add(new Tag(entry.getKey(), entry.getValue() == null ? "" : entry.getValue().toString()));
    }
    tags.add(new Tag("Name", cfg.getFriendlyName()));
    tags.add(new Tag("Description", cfg.getDescription()));
    if (cfg.getVirtualMachineGroup() != null) {
        tags.add(new Tag("dsnVMGroup", cfg.getVirtualMachineGroup()));
    }
    getProvider().createTags(instanceIds.toArray(new String[instanceIds.size()]),
            tags.toArray(new Tag[tags.size()]));

    // Set all instances their passwords and attach volumes
    for (VirtualMachine server : servers) {
        if (cfg.isIpForwardingAllowed()) {
            enableIpForwarding(server.getProviderVirtualMachineId());
        }
        if (cfg.isIpForwardingAllowed()) {
            enableIpForwarding(server.getProviderVirtualMachineId());
        }
        if (server != null && cfg.getBootstrapKey() != null) {
            try {
                final String sid = server.getProviderVirtualMachineId();
                try {
                    Callable<String> callable = new GetPassCallable(sid, getProvider());
                    String password = callable.call();

                    if (password == null) {
                        server.setRootPassword(null);
                        server.setPasswordCallback(callable);
                    } else {
                        server.setRootPassword(password);
                    }
                    server.setPlatform(Platform.WINDOWS);
                } catch (CloudException e) {
                    logger.warn(e.getMessage());
                }
            } catch (Throwable t) {
                logger.warn("Unable to retrieve password for " + server.getProviderVirtualMachineId()
                        + ", Let's hope it's Unix: " + t.getMessage());
            }
        }

        if (!existingVolumes.isEmpty()) {
            final VirtualMachine vm = server;

            getProvider().hold();
            Thread thread = new Thread() {
                public void run() {
                    try {
                        for (VolumeAttachment a : existingVolumes) {
                            try {
                                if (computeServices != null) {
                                    computeServices.getVolumeSupport().attach(a.existingVolumeId,
                                            vm.getProviderMachineImageId(), a.deviceId);
                                }
                            } catch (Throwable t) {
                                // ignore all errors
                            }
                        }
                    } finally {
                        getProvider().release();
                    }
                }
            };

            thread.setName("Volume Mounter for " + server);
            thread.start();
        }
    }
    return servers;
}

From source file:jenkins.model.Jenkins.java

/**
 * Executes a reactor./*  w w  w .j  a  v  a2  s .  c  o m*/
 *
 * @param is
 *      If non-null, this can be consulted for ignoring some tasks. Only used during the initialization of Jenkins.
 */
private void executeReactor(final InitStrategy is, TaskBuilder... builders)
        throws IOException, InterruptedException, ReactorException {
    Reactor reactor = new Reactor(builders) {
        /**
         * Sets the thread name to the task for better diagnostics.
         */
        @Override
        protected void runTask(Task task) throws Exception {
            if (is != null && is.skipInitTask(task))
                return;

            ACL.impersonate(ACL.SYSTEM); // full access in the initialization thread
            String taskName = task.getDisplayName();

            Thread t = Thread.currentThread();
            String name = t.getName();
            if (taskName != null)
                t.setName(taskName);
            try {
                long start = System.currentTimeMillis();
                super.runTask(task);
                if (LOG_STARTUP_PERFORMANCE)
                    LOGGER.info(String.format("Took %dms for %s by %s", System.currentTimeMillis() - start,
                            taskName, name));
            } finally {
                t.setName(name);
                SecurityContextHolder.clearContext();
            }
        }
    };

    new InitReactorRunner() {
        @Override
        protected void onInitMilestoneAttained(InitMilestone milestone) {
            initLevel = milestone;
        }
    }.run(reactor);
}

From source file:edu.umass.cs.gigapaxos.SQLPaxosLogger.java

SQLPaxosLogger(int id, String strID, String dbPath, PaxosMessenger<?> messenger) {
    super(id, dbPath, messenger);
    this.strID = strID;
    GC = Executors.newScheduledThreadPool(2, new ThreadFactory() {
        @Override/*from   www. ja  va 2  s  .c  om*/
        public Thread newThread(Runnable r) {
            Thread thread = Executors.defaultThreadFactory().newThread(r);
            thread.setName(SQLPaxosLogger.class.getSimpleName() + ":" + strID);
            return thread;
        }
    }); // new Timer(strID);
    addDerbyLogger(this);
    this.journaler = new Journaler(this.logDirectory, this.strID/* this.myID */);
    this.deleteTmpJournalFiles();

    this.mapDB = USE_MAP_DB
            ? new MapDBContainer(DBMaker.fileDB(new File(this.getLogIndexDBPrefix())).make(),
                    DBMaker.memoryDB().transactionDisable().make())
            : null;

    Diskable<String, LogIndex> disk = new Diskable<String, LogIndex>() {

        @Override
        public Set<String> commit(Map<String, LogIndex> toCommit) throws IOException {
            return SQLPaxosLogger.this.pauseLogIndex(toCommit);
        }

        @Override
        public LogIndex restore(String key) throws IOException {
            return SQLPaxosLogger.this.unpauseLogIndex(key);
        }

        public String toString() {
            return MessageLogDiskMap.class.getSimpleName() + SQLPaxosLogger.this.strID;
        }

    };
    this.messageLog = USE_MAP_DB ? new MessageLogMapDB(this.mapDB.inMemory, this.mapDB.onDisk, disk)
            : USE_DISK_MAP ? new MessageLogDiskMap(disk) : new MessageLogPausable(disk);

    // will set up db, connection, tables, etc. as needed
    if (!initialize(true))
        throw new RuntimeException("Unable to initiate " + PaxosManager.class.getSimpleName() + " for " + id);
    ;
}

From source file:org.dasein.cloud.aws.compute.EC2Instance.java

private void enableIpForwarding(final String instanceId) throws CloudException {

    Thread t = new Thread() {
        public void run() {
            APITrace.begin(getProvider(), "enableIpForwarding");

            long timeout = System.currentTimeMillis() + CalendarWrapper.MINUTE;

            while (timeout > System.currentTimeMillis()) {
                try {
                    Map<String, String> params = getProvider().getStandardParameters(getProvider().getContext(),
                            EC2Method.MODIFY_INSTANCE_ATTRIBUTE);
                    EC2Method m;//from  w w  w.j av a2 s  . c  o m

                    params.put("InstanceId", instanceId);
                    params.put("SourceDestCheck.Value", "false");
                    m = new EC2Method(getProvider(), params);

                    m.invoke();
                    return;
                } catch (EC2Exception ex) {
                    if (ex.getStatus() != 404) {
                        logger.error("Unable to modify instance attributes on " + instanceId + ".", ex);
                        return;
                    }
                } catch (Throwable ex) {
                    logger.error("Unable to modify instance attributes on " + instanceId + ".", ex);
                    return;
                } finally {
                    APITrace.end();
                }

                try {
                    Thread.sleep(5000L);
                } catch (InterruptedException ignore) {
                }
            }

        }
    };

    t.setName(EC2Method.MODIFY_INSTANCE_ATTRIBUTE + " thread");
    t.setDaemon(true);
    t.start();

}

From source file:uk.ac.ebi.mdk.apps.tool.Align2Reference.java

@Override
public void process() {

    System.out.print("Reading query...");
    final Reconstruction query = getReconstruction("query");
    System.out.println("done");
    System.out.print("Reading reference...");
    final Reconstruction reference = getReconstruction("reference");
    System.out.println("done");

    System.out.printf("    Query reconstruction %20s %6s,%6s\n", query.getAccession(),
            query.getMetabolome().size(), query.getReactome().size());
    System.out.printf("Reference reconstruction %20s %6s,%6s\n", reference.getAccession(),
            reference.getMetabolome().size(), reference.getReactome().size());

    if (has("profile")) {
        // break point for starting visual vm

        Scanner scanner = new Scanner(System.in);
        System.out.print("Ready to go? [y/n]:\n");
        while (!scanner.nextLine().equalsIgnoreCase("y")) {

            // await signal
            System.out.println("Okay, let me know");
            System.out.print("Ready to go? [y/n]:");
        }/*from   ww w  .  j ava 2  s .  c om*/
    }

    MolecularHashFactory.getInstance().setDepth(1);

    final EntityAligner<Metabolite> aligner = new MappedEntityAligner<Metabolite>(
            reference.getMetabolome().toList(), false);

    final List<MetaboliteHashCodeMatcher> hashCodeMatchers = new ArrayList<MetaboliteHashCodeMatcher>();
    hashCodeMatchers.add(new MetaboliteHashCodeMatcher(AtomicNumberSeed.class, BondOrderSumSeed.class,
            StereoSeed.class, ConnectedAtomSeed.class, ChargeSeed.class));
    hashCodeMatchers.add(new MetaboliteHashCodeMatcher(AtomicNumberSeed.class, BondOrderSumSeed.class,
            ConnectedAtomSeed.class, StereoSeed.class));
    hashCodeMatchers.add(new MetaboliteHashCodeMatcher(AtomicNumberSeed.class, BondOrderSumSeed.class,
            ConnectedAtomSeed.class, ChargeSeed.class));

    aligner.push(new DirectMatcher<Metabolite>());
    aligner.push(new MetaboliteHashCodeMatcher(AtomicNumberSeed.class, BondOrderSumSeed.class, StereoSeed.class,
            ConnectedAtomSeed.class, ChargeSeed.class));
    aligner.push(new MetaboliteHashCodeMatcher(AtomicNumberSeed.class, BondOrderSumSeed.class,
            ConnectedAtomSeed.class, StereoSeed.class));
    aligner.push(new MetaboliteHashCodeMatcher(AtomicNumberSeed.class, BondOrderSumSeed.class,
            ConnectedAtomSeed.class, ChargeSeed.class));
    aligner.push(new MetaboliteHashCodeMatcher(AtomicNumberSeed.class, BondOrderSumSeed.class,
            ConnectedAtomSeed.class));
    aligner.push(new NameMatcher<Metabolite>());
    aligner.push(new NameMatcher<Metabolite>(true, true));

    final EntityMatcher<Metabolite, ?> nameMatcher = new NameMatcher<Metabolite>(true, true);

    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {

            Collection<Metabolite> unmatched = new ArrayList<Metabolite>();
            Collection<Multimap<Metabolite, Metabolite>> mismatched = new ArrayList<Multimap<Metabolite, Metabolite>>();

            int matched = 0;

            long start = System.currentTimeMillis();

            for (Metabolite m : query.getMetabolome()) {

                List<Metabolite> matches = aligner.getMatches(m);
                matched += matches.isEmpty() ? 0 : 1;

                if (matches.isEmpty()) {
                    unmatched.add(m);
                }

                //                    for (Metabolite r : matches) {
                //                        if (!nameMatcher.matches(m, r)) {
                //                            Multimap multimap = HashMultimap.create();
                //                            multimap.putAll(m, matches);
                //                            mismatched.add(multimap);
                //                            break;
                //                        }
                //                    }

            }

            long end = System.currentTimeMillis();

            System.out.println("Completed in " + (end - start) + " ms");
            System.out.println("Matched " + matched + "/" + query.getMetabolome().size() + " entities");
            System.out.println("Structure mismatch " + mismatched.size());

            try {
                File tmp = File.createTempFile("unmatched", ".tsv");
                CSVWriter writer = new CSVWriter(new FileWriter(tmp), '\t');
                for (Metabolite m : unmatched) {
                    writer.writeNext(new String[] { m.getAccession(), m.getName(),
                            m.getAnnotationsExtending(CrossReference.class).toString() });
                }
                writer.close();

                System.out.println("Unmatched entries written to: " + tmp);

            } catch (IOException e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            }
            try {
                File tmp = File.createTempFile("miss-matched", ".tsv");
                CSVWriter writer = new CSVWriter(new FileWriter(tmp), '\t');
                for (Multimap<Metabolite, Metabolite> emap : mismatched) {
                    for (Map.Entry<Metabolite, Metabolite> e : emap.entries()) {

                        List<Set<Integer>> qh = new ArrayList<Set<Integer>>();
                        List<Set<Integer>> rh = new ArrayList<Set<Integer>>();

                        for (MetaboliteHashCodeMatcher matcher : hashCodeMatchers) {
                            qh.add(matcher.calculatedMetric(e.getKey()));
                        }
                        for (MetaboliteHashCodeMatcher matcher : hashCodeMatchers) {
                            rh.add(matcher.calculatedMetric(e.getValue()));
                        }

                        writer.writeNext(new String[] { e.getKey().getAccession(), e.getKey().getName(),
                                e.getKey().getAnnotationsExtending(CrossReference.class).toString(),

                                e.getValue().getAccession(), e.getValue().getName(),
                                e.getValue().getAnnotationsExtending(CrossReference.class).toString(), "",
                                Joiner.on(", ").join(qh), Joiner.on(", ").join(rh) });
                    }
                }
                writer.close();

                System.out.println("Miss-matched entries written to: " + tmp);

            } catch (IOException e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            }

        }
    });
    t.setName("METABOLOME ALIGNMENT");
    t.start();
    try {
        t.join();
    } catch (InterruptedException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }

    final Map<Metabolite, Integer> countMap = new HashMap<Metabolite, java.lang.Integer>();
    Reactome reactome = query.getReactome();
    for (Metabolite m : query.getMetabolome()) {
        countMap.put(m, reactome.participatesIn(m).size());
    }

    System.out.println("Most common metabolites:");
    for (Map.Entry<Metabolite, Integer> e : entriesSortedByValues(countMap)) {
        if (e.getValue() > 40) {
            System.out.println(e.getKey() + ":" + e.getKey().hashCode() + ":" + e.getValue());
        }
    }

    Set<Metabolite> queryCurrencyMetabolites = new HashSet<Metabolite>();
    Set<Metabolite> referenceCurrencyMetabolites = new HashSet<Metabolite>();
    queryCurrencyMetabolites.addAll(query.getMetabolome().ofName("H+"));
    queryCurrencyMetabolites.addAll(query.getMetabolome().ofName("H2O"));
    queryCurrencyMetabolites.addAll(query.getMetabolome().ofName("CO2"));
    queryCurrencyMetabolites.addAll(query.getMetabolome().ofName("ammonium"));
    queryCurrencyMetabolites.addAll(query.getMetabolome().ofName("ammonia"));
    referenceCurrencyMetabolites.addAll(reference.getMetabolome().ofName("H+"));
    referenceCurrencyMetabolites.addAll(reference.getMetabolome().ofName("H2O"));
    referenceCurrencyMetabolites.addAll(reference.getMetabolome().ofName("CO2"));
    referenceCurrencyMetabolites.addAll(reference.getMetabolome().ofName("ammonium"));
    referenceCurrencyMetabolites.addAll(reference.getMetabolome().ofName("ammonia"));
    referenceCurrencyMetabolites.addAll(reference.getMetabolome().ofName("Phosphate"));

    int count = 0;
    int transport = 0;

    System.out.println();
    System.out.println("| REACTOME ALIGNMENT |");

    EntityAligner<MetabolicReaction> reactionAligner = new MappedEntityAligner<MetabolicReaction>(
            reference.reactome().toList());

    reactionAligner.push(new ReactionMatcher(aligner));
    reactionAligner.push(new ReactionMatcher(aligner, false));
    reactionAligner.push(new ReactionMatcher(aligner, true,
            Collections.singleton(reference.getMetabolome().ofName("H+").iterator().next())));
    reactionAligner.push(new ReactionMatcher(aligner, false,
            Collections.singleton(reference.getMetabolome().ofName("H+").iterator().next())));
    reactionAligner.push(new ReactionMatcher(aligner, false,
            new HashSet<Metabolite>(Arrays.asList(reference.getMetabolome().ofName("H+").iterator().next(),
                    reference.getMetabolome().ofName("H2O").iterator().next()))));
    reactionAligner.push(new ReactionMatcher(aligner, false, referenceCurrencyMetabolites));

    for (MetabolicReaction reaction : reactome) {

        // skip transport reactsions for now
        if (TransportReactionUtil.isTransport(reaction)) {
            transport++;
            continue;
        }

        System.out.println(reaction.getIdentifier() + ": " + reaction);

        Collection<MetabolicReaction> matches = reactionAligner.getMatches(reaction);
        for (MetabolicReaction rxnMatch : matches) {
            System.out.println("\t" + rxnMatch);
        }

        count += matches.isEmpty() ? 1 : 0;

        if (true)
            continue;

        Map<Identifier, MutableInt> reactionReferences = new HashMap<Identifier, MutableInt>();

        for (Participant<Metabolite, ?> p : reaction.getParticipants()) {

            Metabolite m = p.getMolecule();

            System.out.print("\t" + m.getName() + " == ");

            for (Metabolite r : aligner.getMatches(m)) {

                System.out.print(r + " ");

                for (Reaction rxnRef : reference.participatesIn(r)) {

                    Identifier identifier = rxnRef.getIdentifier();

                    if (!reactionReferences.containsKey(identifier)) {
                        reactionReferences.put(identifier, new MutableInt());
                    }

                    reactionReferences.get(identifier).increment();

                }
            }

            System.out.println();

        }

        Map<Identifier, MetabolicReaction> idToReaction = new HashMap<Identifier, MetabolicReaction>();
        for (MetabolicReaction r : reference.reactome()) {
            idToReaction.put(r.getIdentifier(), r);
        }

        System.out.println("Candidate matches for " + reaction);
        for (Map.Entry<Identifier, MutableInt> e : reactionReferences.entrySet()) {

            int nParticipants = e.getValue().toInteger();

            if (nParticipants >= adjustedCount(reaction, queryCurrencyMetabolites)) {

                Collection<MetabolicParticipant> refps = adjustedParticipants(idToReaction.get(e.getKey()),
                        referenceCurrencyMetabolites);

                boolean show = true;

                MetabolicReaction referenceReaction = idToReaction.get(e.getKey());

                System.out.println(referenceReaction);

                for (Participant<Metabolite, ?> p : adjustedParticipants(reaction, queryCurrencyMetabolites)) {

                    List<Metabolite> referenceMetabolites = aligner.getMatches(p.getMolecule());

                    if (referenceMetabolites.isEmpty()) {
                        // missing reference
                        show = false;
                        break;
                    }

                    if (referenceMetabolites.size() > 1) {
                        // complex case
                        show = false;
                        break;
                    }

                    Metabolite r = referenceMetabolites.get(0);
                    boolean found = false;
                    MetabolicParticipant remove = null;
                    for (MetabolicParticipant rp : refps) {
                        if (rp.getMolecule().equals(r)) {
                            found = true;
                            remove = rp;
                            break;
                        }
                    }

                    if (!found) {
                        show = false;
                    } else {
                        refps.remove(remove);
                    }

                }

                // matches
                if (show && refps.isEmpty()) {
                    System.out.println("\t [match] " + referenceReaction);
                    //                        MetabolicReaction rxn1 = m2.calculatedMetric(reaction).iterator().readNext();
                    //                        MetabolicReaction rxn2 = m2.calculatedMetric(referenceReaction).iterator().readNext();
                    //                        System.out.println(rxn1.hashCode());
                    //                        System.out.println(rxn2.hashCode());
                    //                        System.out.println(rxn1.equals(rxn2));

                }
            }

        }

    }

    System.out.println(count + "/" + query.getReactome().size()
            + " were not matched (transport reactions skipped by default) n transport reactions = "
            + transport);

}

From source file:org.energy_home.jemma.javagal.layers.data.implementations.IDataLayerImplementation.DataFreescale.java

@Override
public void notifyFrame(final ByteArrayObject frame) {
    Thread thr = new Thread() {
        @Override//from ww w.  j  ava 2s.  c o  m
        public void run() {
            try {

                byte[] msg = frame.getByteArray();
                int size = frame.getByteCount(true);

                short[] messageShort = new short[size];
                for (int i = 0; i < size; i++)
                    messageShort[i] = (short) (msg[i] & 0xff);

                if (gal.getPropertiesManager().getDebugEnabled())
                    DataManipulation.logArrayHexRadixDataReceived("<<< Received data: ", messageShort);
                addToReceivedDataQueue(size, messageShort);
                try {
                    processMessages();
                } catch (Exception e) {
                    if (gal.getPropertiesManager().getDebugEnabled())
                        logger.error("Error on notifyFrame:" + e.getMessage());
                }
            } catch (Exception e) {
                if (gal.getPropertiesManager().getDebugEnabled())
                    logger.error("Error on notifyFrame: " + e.getMessage());
            }
        }
    };
    thr.setName("Thread notifyFrame");
    thr.start();
}

From source file:org.energy_home.jemma.javagal.layers.data.implementations.IDataLayerImplementation.DataFreescale.java

public void processMessages() throws Exception {
    // Look on received messages
    int _size = 0;
    synchronized (this) {
        _size = messages.size();//from w w  w.  j a v a2  s .  c  o  m
    }

    while (_size > 0) {
        short[] message = null;
        synchronized (this) {
            message = messages.remove(0);
        }

        ByteBuffer bb = ByteBuffer.allocate(2);
        bb.order(ByteOrder.BIG_ENDIAN);
        bb.put((byte) message[0]);
        bb.put((byte) message[1]);
        short _command = bb.getShort(0);

        /* APSDE-DATA.Indication */
        if (_command == FreescaleConstants.APSDEDataIndication) {
            final APSMessageEvent messageEvent = new APSMessageEvent();
            short destAddressMode = message[3];
            messageEvent.setDestinationAddressMode((long) destAddressMode);
            BigInteger _ieee = null;
            Address address = new Address();
            switch (destAddressMode) {
            case 0x00:
                // Reserved (No source address supplied)
                if (gal.getPropertiesManager().getDebugEnabled()) {
                    logger.info("Message Discarded: found reserved 0x00 as Destination Address Mode ");
                } // Error found, we don't proceed and discard the
                  // message
                return;
            case 0x01:
                // Value16bitgroupfordstAddr (DstEndpoint not
                // present)
                // No destination end point (so FF broadcast),
                // present
                // short
                // address on 2 bytes
                address.setNetworkAddress(
                        DataManipulation.toIntFromShort((byte) message[5], (byte) message[4]));

                _ieee = gal.getIeeeAddress_FromNetworkCache(address.getNetworkAddress());
                if (_ieee != null)
                    address.setIeeeAddress(_ieee);

                messageEvent.setDestinationAddress(address);
                messageEvent.setDestinationEndpoint((short) 0xff);

                break;
            case 0x02:
                // Value16bitAddrandDstEndpoint (16 bit address
                // supplied)
                address.setNetworkAddress(
                        DataManipulation.toIntFromShort((byte) message[5], (byte) message[4]));
                _ieee = gal.getIeeeAddress_FromNetworkCache(address.getNetworkAddress());
                if (_ieee != null)
                    address.setIeeeAddress(_ieee);

                messageEvent.setDestinationAddress(address);
                messageEvent.setDestinationEndpoint(message[6]);
                break;
            default:
                if (gal.getPropertiesManager().getDebugEnabled()) {
                    logger.error("Message Discarded: not valid Destination Address Mode");
                }
                // Error found, we don't proceed and discard the
                // message
                return;
            }
            messageEvent.setSourceAddressMode((long) message[7]);
            address = new Address();
            address.setNetworkAddress(DataManipulation.toIntFromShort((byte) message[9], (byte) message[8]));
            _ieee = gal.getIeeeAddress_FromNetworkCache(address.getNetworkAddress());
            if (_ieee != null)
                address.setIeeeAddress(_ieee);
            messageEvent.setSourceAddress(address);
            messageEvent.setSourceEndpoint(message[10]);
            messageEvent.setProfileID(DataManipulation.toIntFromShort((byte) message[12], (byte) message[11]));
            messageEvent.setClusterID(DataManipulation.toIntFromShort((byte) message[14], (byte) message[13]));

            if (gal.getGatewayStatus() == GatewayStatus.GW_RUNNING && gal.get_GalNode() != null) {
                /* Update The Node Data */

                int _indexOnCache = -1;
                _indexOnCache = gal.existIntoNetworkCache(address.getNetworkAddress());
                if (_indexOnCache != -1) {
                    /* The node is already into the DB */
                    if (gal.getPropertiesManager().getKeepAliveThreshold() > 0) {
                        if (!gal.getNetworkcache().get(_indexOnCache).isSleepy()) {
                            gal.getNetworkcache().get(_indexOnCache).reset_numberOfAttempt();
                            gal.getNetworkcache().get(_indexOnCache)
                                    .setTimerFreshness(gal.getPropertiesManager().getKeepAliveThreshold());
                            if (gal.getPropertiesManager().getDebugEnabled()) {
                                //System.out.println("\n\rPostponing  timer Freshness by Aps.Indication for node:" + gal.getNetworkcache().get(_indexOnCache).get_node().getAddress().getNetworkAddress() + "\n\r");
                                logger.info("Postponing  timer Freshness by Aps.Indication for node:"
                                        + gal.getNetworkcache().get(_indexOnCache).get_node().getAddress()
                                                .getNetworkAddress());
                            }
                        }

                    }
                } else {
                    // 0x8034 is a LeaveAnnouncement, 0x0013 is a
                    // DeviceAnnouncement, 0x8001 is a IEEE_Addr_Rsp
                    if ((gal.getPropertiesManager().getAutoDiscoveryUnknownNodes() > 0)
                            && (!(messageEvent.getProfileID() == 0x0000
                                    && (messageEvent.getClusterID() == 0x0013
                                            || messageEvent.getClusterID() == 0x8034
                                            || messageEvent.getClusterID() == 0x8001)))) {

                        if (address.getNetworkAddress() != gal.get_GalNode().get_node().getAddress()
                                .getNetworkAddress()) {
                            Runnable thr = new MyThread(address) {
                                @Override
                                public void run() {
                                    Address _address = (Address) this.getParameter();
                                    int _indexOnCache = -1;
                                    _indexOnCache = gal.existIntoNetworkCache(_address.getNetworkAddress());
                                    if (_indexOnCache == -1) {

                                        if (gal.getPropertiesManager().getDebugEnabled()) {
                                            //System.out.println("\n\rAutoDiscoveryUnknownNodes procedure of Node:" + messageEvent.getSourceAddress().getNetworkAddress() + "\n\r");

                                            logger.info("AutoDiscoveryUnknownNodes procedure of Node:"
                                                    + messageEvent.getSourceAddress().getNetworkAddress());
                                        }
                                        try {

                                            // Insert the node into cache,
                                            // but with the
                                            // discovery_completed flag a
                                            // false
                                            BigInteger ieee = null;
                                            WrapperWSNNode o = new WrapperWSNNode(gal);
                                            WSNNode _newNode = new WSNNode();
                                            o.set_discoveryCompleted(false);
                                            _newNode.setAddress(_address);
                                            o.set_node(_newNode);
                                            gal.getNetworkcache().add(o);

                                            Thread.sleep(500);
                                            /*
                                             * Reading the IEEEAddress of
                                             * the new node
                                             */

                                            if (gal.getPropertiesManager().getDebugEnabled())
                                                logger.info(
                                                        "Sending IeeeReq to:" + _address.getNetworkAddress());
                                            System.out.println(
                                                    "Sending IeeeReq to:" + _address.getNetworkAddress());
                                            ieee = readExtAddress(INTERNAL_TIMEOUT,
                                                    _address.getNetworkAddress().shortValue());
                                            _address.setIeeeAddress(ieee);
                                            if (gal.getPropertiesManager().getDebugEnabled()) {
                                                logger.info("Readed Ieee of the new node:"
                                                        + _address.getNetworkAddress() + " Ieee: "
                                                        + ieee.toString());
                                                System.out.println("Readed Ieee of the new node:"
                                                        + _address.getNetworkAddress() + " Ieee: "
                                                        + ieee.toString());

                                            }
                                            if (gal.getPropertiesManager().getDebugEnabled())
                                                logger.info("Sending NodeDescriptorReq to:"
                                                        + _address.getNetworkAddress());
                                            NodeDescriptor _ndesc = getNodeDescriptorSync(INTERNAL_TIMEOUT,
                                                    _address);
                                            _newNode.setCapabilityInformation(_ndesc.getMACCapabilityFlag());

                                            if (gal.getPropertiesManager().getDebugEnabled()) {
                                                logger.info("Readed NodeDescriptor of the new node:"
                                                        + _address.getNetworkAddress());
                                                System.out.println("Readed NodeDescriptor of the new node:"
                                                        + _address.getNetworkAddress());

                                            }

                                            o.reset_numberOfAttempt();
                                            o.set_discoveryCompleted(true);
                                            if (!o.isSleepy()) {

                                                if (gal.getPropertiesManager().getKeepAliveThreshold() > 0) {
                                                    o.setTimerFreshness(
                                                            gal.getPropertiesManager().getKeepAliveThreshold());
                                                }
                                                if (gal.getPropertiesManager().getForcePingTimeout() > 0) {
                                                    o.setTimerForcePing(
                                                            gal.getPropertiesManager().getForcePingTimeout());
                                                }
                                            }

                                            _indexOnCache = gal.existIntoNetworkCache(
                                                    _newNode.getAddress().getNetworkAddress());
                                            if (_indexOnCache > -1) {
                                                gal.getNetworkcache().remove(_indexOnCache);

                                            }

                                            // Updating the node
                                            // informations
                                            gal.getNetworkcache().add(o);
                                            o.set_discoveryCompleted(true);
                                            Status _st = new Status();
                                            _st.setCode((short) GatewayConstants.SUCCESS);
                                            gal.get_gatewayEventManager().nodeDiscovered(_st, _newNode);

                                        } catch (GatewayException e) {
                                            logger.error("Error on getAutoDiscoveryUnknownNodes for node:"
                                                    + _address.getNetworkAddress() + " Error:"
                                                    + e.getMessage());

                                            System.out.println("Error on getAutoDiscoveryUnknownNodes for node:"
                                                    + _address.getNetworkAddress() + " Error:"
                                                    + e.getMessage());

                                            _indexOnCache = gal
                                                    .existIntoNetworkCache(_address.getNetworkAddress());
                                            if (_indexOnCache > -1) {
                                                gal.getNetworkcache().get(_indexOnCache).abortTimers();
                                                gal.getNetworkcache().remove(_indexOnCache);
                                            }

                                        } catch (Exception e) {
                                            logger.error("Error on getAutoDiscoveryUnknownNodes for node:"
                                                    + _address.getNetworkAddress() + " Error:"
                                                    + e.getMessage());
                                            System.out.println("Error on getAutoDiscoveryUnknownNodes for node:"
                                                    + _address.getNetworkAddress() + " Error:"
                                                    + e.getMessage());
                                            _indexOnCache = gal
                                                    .existIntoNetworkCache(_address.getNetworkAddress());
                                            if (_indexOnCache > -1) {
                                                gal.getNetworkcache().get(_indexOnCache).abortTimers();
                                                gal.getNetworkcache().remove(_indexOnCache);

                                            }

                                        }
                                    }
                                }
                            };

                            Thread _thr0 = new Thread(thr);
                            _thr0.setName("Thread getAutoDiscoveryUnknownNodes:" + address.getNetworkAddress());
                            _thr0.start();
                        }
                    }
                }

            }
            int lastAsdu = 16 + message[15] - 1;

            messageEvent.setData(DataManipulation.subByteArray(message, 16, lastAsdu));
            messageEvent.setAPSStatus(message[lastAsdu + 1]);
            // ASK Jump WasBroadcast
            // Security Status
            switch (message[lastAsdu + 3]) {
            case 0x00:
                messageEvent.setSecurityStatus(SecurityStatus.UNSECURED);
                break;
            case 0x01:
                messageEvent.setSecurityStatus(SecurityStatus.SECURED_NWK_KEY);
                break;
            case 0x02:
                messageEvent.setSecurityStatus(SecurityStatus.SECURED_LINK_KEY);
                break;
            // ASK 0x03 not present on telecomitalia object
            default:
                if (gal.getPropertiesManager().getDebugEnabled()) {
                    logger.info("Message Discarded: not valid Security Status");
                }
                // Error found, we don't proceed and discard the
                // message
                return;
            }
            messageEvent.setLinkQuality(message[lastAsdu + 4]);
            messageEvent.setRxTime((long) DataManipulation.toIntFromShort((byte) message[(lastAsdu + 8)],
                    (byte) message[(lastAsdu + 5)]));
            // ASK: jumped iMsgType, pNext, iDataSize, pData,
            // iBufferNumber
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix("Extracted APSDE-DATA.Indication", message);
            if ((messageEvent.getDestinationAddressMode() == GatewayConstants.ADDRESS_MODE_SHORT)
                    && (messageEvent.getDestinationAddress().getIeeeAddress() == null))
                messageEvent.getDestinationAddress().setIeeeAddress(gal.getIeeeAddress_FromNetworkCache(
                        messageEvent.getDestinationAddress().getNetworkAddress()));

            if ((messageEvent.getDestinationAddressMode() == GatewayConstants.EXTENDED_ADDRESS_MODE)
                    && (messageEvent.getDestinationAddress().getNetworkAddress() == null))
                messageEvent.getDestinationAddress().setNetworkAddress(gal.getShortAddress_FromNetworkCache(
                        messageEvent.getDestinationAddress().getIeeeAddress()));

            if ((messageEvent.getSourceAddressMode() == GatewayConstants.ADDRESS_MODE_SHORT)
                    && (messageEvent.getDestinationAddress().getIeeeAddress() == null))
                messageEvent.getSourceAddress().setIeeeAddress(gal
                        .getIeeeAddress_FromNetworkCache(messageEvent.getSourceAddress().getNetworkAddress()));

            if ((messageEvent.getSourceAddressMode() == GatewayConstants.EXTENDED_ADDRESS_MODE)
                    && (messageEvent.getDestinationAddress().getNetworkAddress() == null))
                messageEvent.getSourceAddress().setNetworkAddress(
                        gal.getShortAddress_FromNetworkCache(messageEvent.getSourceAddress().getIeeeAddress()));

            if (messageEvent.getProfileID().equals(0)) {/*
                                                        * ZDO Command
                                                        */
                if (messageEvent.getClusterID() == 0x8031) {
                    String __key = "";
                    __key = String.format("%04X", messageEvent.getSourceAddress().getNetworkAddress());
                    synchronized (listLocker) {
                        for (ParserLocker pl : listLocker) {
                            if ((pl.getType() == TypeMessage.LQI_REQ) && __key.equalsIgnoreCase(pl.get_Key())) {
                                synchronized (pl) {
                                    pl.getStatus().setCode((short) messageEvent.getAPSStatus());
                                    Mgmt_LQI_rsp _res = new Mgmt_LQI_rsp(messageEvent.getData());
                                    pl.set_objectOfResponse(_res);
                                    pl.notify();
                                }
                                break;
                            }
                        }
                    }
                }
                // profileid == 0
                gal.getZdoManager().ZDOMessageIndication(messageEvent);
            } else {
                // profileid > 0
                ZCLMessage _zm = new ZCLMessage();
                _zm.setAPSStatus(messageEvent.getAPSStatus());
                _zm.setClusterID(messageEvent.getClusterID());
                _zm.setDestinationEndpoint(messageEvent.getDestinationEndpoint());
                _zm.setProfileID(messageEvent.getProfileID());
                _zm.setRxTime(messageEvent.getRxTime());
                _zm.setSourceAddress(messageEvent.getSourceAddress());
                _zm.setSourceAddressMode(messageEvent.getSourceAddressMode());
                _zm.setSourceEndpoint(messageEvent.getSourceEndpoint());

                byte[] data = messageEvent.getData();
                // ZCL Header
                // Frame control 8bit
                // Manufacturer code 0/16bits
                // Transaction sequence number 8bit
                // Command identifier 8 bit
                ByteArrayObject _header = new ByteArrayObject();
                ByteArrayObject _payload = new ByteArrayObject();
                if ((data[0] & 0x04) == 1)/* Check manufacturer code */
                {
                    _header.addByte(data[0]);// Frame control
                    _header.addByte(data[1]);// Manufacturer Code(1/2)
                    _header.addByte(data[2]);// Manufacturer Code(2/2)
                    _header.addByte(data[3]);// Transaction sequence number
                    _header.addByte(data[4]);// Command Identifier
                    for (int i = 5; i < data.length; i++)
                        _payload.addByte(data[i]);
                } else {
                    _header.addByte(data[0]);// Frame control
                    _header.addByte(data[1]);// Transaction sequence number
                    _header.addByte(data[2]);// Command Identifier
                    for (int i = 3; i < data.length; i++)
                        _payload.addByte(data[i]);
                }

                _zm.setZCLHeader(_header.getRealByteArray());
                _zm.setZCLPayload(_payload.getRealByteArray());
                gal.get_gatewayEventManager().notifyZCLCommand(_zm);
                gal.getApsManager().APSMessageIndication(messageEvent);

            }
        }

        /* APSDE-DATA.Confirm */
        else if (_command == FreescaleConstants.APSDEDataConfirm) {
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix("Extracted APSDE-DATA.Confirm", message);

            /* DestAddress + DestEndPoint + SourceEndPoint */
            long destAddress = DataManipulation.toLong((byte) message[11], (byte) message[10],
                    (byte) message[9], (byte) message[8], (byte) message[7], (byte) message[6],
                    (byte) message[5], (byte) message[4]);
            byte destEndPoint = (byte) message[12];
            byte sourceEndPoint = (byte) message[13];
            String Key = String.format("%016X", destAddress) + String.format("%02X", destEndPoint)
                    + String.format("%02X", sourceEndPoint);

            // Found APSDE-DATA.Confirm. Remove the lock
            synchronized (listLocker) {
                for (ParserLocker pl : listLocker) {
                    /* DestAddress + DestEndPoint + SourceEndPoint */
                    /*
                     * if (gal.getPropertiesManager().getDebugEnabled())
                     * logger.info("APSDE-DATA.Confirm KEY SEND: " +
                     * pl.get_Key() + " -- KEY Received: " + Key);
                     */
                    if ((pl.getType() == TypeMessage.APS) && pl.get_Key().equalsIgnoreCase(Key)) {
                        synchronized (pl) {
                            pl.getStatus().setCode(message[14]);
                            pl.notify();
                        }
                        break;
                    }
                }
            }

        }

        /* ZTC-Error.event */
        else if (_command == FreescaleConstants.ZTCErrorevent) {

            byte len = (byte) message[2];
            String MessageStatus = "";
            if (len > 0) {
                int status = message[3];
                switch (status) {
                case 0x00:
                    MessageStatus = "0x00: gSuccess_c (Should not be seen in this event.)";
                    break;
                case 0xF4:
                    MessageStatus = "0xF4: gZtcOutOfMessages_c (ZTC tried to allocate a message, but the allocation failed.)";
                    break;
                case 0xF5:
                    MessageStatus = "0xF5: gZtcEndPointTableIsFull_c (Self explanatory.)";
                    break;
                case 0xF6:
                    MessageStatus = "0xF6: gZtcEndPointNotFound_c (Self explanatory.)";
                    break;
                case 0xF7:
                    MessageStatus = "0xF7: gZtcUnknownOpcodeGroup_c (ZTC does not recognize the opcode group, and there is no application hook.)";
                    break;
                case 0xF8:
                    MessageStatus = "0xF8: gZtcOpcodeGroupIsDisabled_c (ZTC support for an opcode group is turned off by a compile option.)";
                    break;
                case 0xF9:
                    MessageStatus = "0xF9: gZtcDebugPrintFailed_c (An attempt to print a debug message ran out of buffer space.)";
                    break;
                case 0xFA:
                    MessageStatus = "0xFA: gZtcReadOnly_c (Attempt to set read-only data.)";
                    break;
                case 0xFB:
                    MessageStatus = "0xFB: gZtcUnknownIBIdentifier_c (Self explanatory.)";
                    break;
                case 0xFC:
                    MessageStatus = "0xFC: gZtcRequestIsDisabled_c (ZTC support for an opcode is turned off by a compile option.)";
                    break;
                case 0xFD:
                    MessageStatus = "0xFD: gZtcUnknownOpcode_c (Self expanatory.)";
                    break;
                case 0xFE:
                    MessageStatus = "0xFE: gZtcTooBig_c (A data item to be set or retrieved is too big for the buffer available to hold it.)";
                    break;
                case 0xFF:
                    MessageStatus = "0xFF: gZtcError_c (Non-specific, catchall error code.)";
                    break;
                default:
                    break;
                }

            }
            String logMessage = "Extracted ZTC-ERROR.Event Status:" + MessageStatus;
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix(logMessage, message);
        }

        /* ZDP-Mgmt_Nwk_Update.Notify */

        else if (_command == FreescaleConstants.ZDPMgmt_Nwk_UpdateNotify) {
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix("Extracted ZDP-Mgmt_Nwk_Update.Notify", message);

            synchronized (listLocker) {
                for (ParserLocker pl : listLocker) {
                    if (pl.getType() == TypeMessage.NWK_UPDATE) {

                        EnergyScanResult _result = new EnergyScanResult();

                        int _address = DataManipulation.toIntFromShort((byte) message[4], (byte) message[3]);

                        short _status = message[5];
                        if (_status == GatewayConstants.SUCCESS) {
                            byte[] _scannedChannel = new byte[4];
                            _scannedChannel[0] = (byte) message[9];
                            _scannedChannel[1] = (byte) message[8];
                            _scannedChannel[2] = (byte) message[7];
                            _scannedChannel[3] = (byte) message[6];

                            int _totalTrasmission = DataManipulation.toIntFromShort((byte) message[11],
                                    (byte) message[10]);

                            int _trasmissionFailure = DataManipulation.toIntFromShort((byte) message[13],
                                    (byte) message[12]);

                            short _scannedChannelListCount = message[14];
                            for (int i = 0; i < _scannedChannelListCount; i++) {
                                ScannedChannel _sc = new ScannedChannel();
                                // _sc.setChannel(value)
                                _sc.setEnergy(message[15 + i]);

                                _result.getScannedChannel().add(_sc);
                            }
                            synchronized (pl) {
                                pl.getStatus().setCode(message[7]);
                                pl.set_objectOfResponse(_result);
                                pl.notify();
                            }
                            break;

                        }

                    }
                }
            }

        }

        /* ZDP-SimpleDescriptor.Response */
        else if (_command == FreescaleConstants.ZDPSimpleDescriptorResponse) {
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix("Extracted ZDP-ExtendedSimpleDescriptor.Response", message);
            /* Address + EndPoint */
            Address _add = new Address();

            _add.setNetworkAddress(DataManipulation.toIntFromShort((byte) message[5], (byte) message[4]));
            byte EndPoint = (byte) message[7];
            String Key = String.format("%04X", _add.getNetworkAddress()) + String.format("%02X", EndPoint);
            // Found ZDP-SimpleDescriptor.Response. Remove the lock
            synchronized (listLocker) {
                for (ParserLocker pl : listLocker) {
                    /* Address + EndPoint */
                    if ((pl.getType() == TypeMessage.GET_SIMPLE_DESCRIPTOR)
                            && pl.get_Key().equalsIgnoreCase(Key)) {

                        synchronized (pl) {
                            pl.getStatus().setCode(message[3]);
                            if (pl.getStatus().getCode() == GatewayConstants.SUCCESS) {

                                SimpleDescriptor _sp = new SimpleDescriptor();
                                _sp.setApplicationProfileIdentifier(
                                        DataManipulation.toIntFromShort((byte) message[9], (byte) message[8]));
                                _sp.setApplicationDeviceIdentifier(DataManipulation
                                        .toIntFromShort((byte) message[11], (byte) message[10]));
                                _sp.setApplicationDeviceVersion(message[12]);
                                int _index = 14;
                                short _numInpCluster = message[13];
                                for (int i = 0; i < _numInpCluster; i++) {
                                    _sp.getApplicationInputCluster().add(DataManipulation.toIntFromShort(
                                            (byte) message[_index + 1], (byte) message[_index]));
                                    _index = _index + 2;
                                }

                                short _numOutCluster = message[_index++];

                                for (int i = 0; i < _numOutCluster; i++) {
                                    _sp.getApplicationOutputCluster().add(DataManipulation.toIntFromShort(
                                            (byte) message[_index + 1], (byte) message[_index]));
                                    _index = _index + 2;
                                }
                                ServiceDescriptor _toRes = new ServiceDescriptor();
                                _toRes.setAddress(_add);
                                _toRes.setEndPoint(EndPoint);
                                _toRes.setSimpleDescriptor(_sp);
                                pl.set_objectOfResponse(_toRes);
                            }
                            pl.notify();
                        }
                        break;
                    }
                }
            }

        }

        /* APS-GetEndPointIdList.Confirm */
        else if (_command == FreescaleConstants.APSGetEndPointIdListConfirm) {
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix("Extracted APS-GetEndPointIdList.Confirm", message);
            synchronized (listLocker) {
                for (ParserLocker pl : listLocker) {
                    if ((pl.getType() == TypeMessage.GET_END_POINT_LIST)) {
                        synchronized (pl) {
                            pl.getStatus().setCode(message[3]);
                            NodeServices _res = new NodeServices();
                            if (pl.getStatus().getCode() == GatewayConstants.SUCCESS) {
                                short length = message[4];
                                for (int i = 0; i < length; i++) {
                                    ActiveEndpoints _ep = new ActiveEndpoints();
                                    _ep.setEndPoint(message[5 + i]);
                                    _res.getActiveEndpoints().add(_ep);
                                }
                            }
                            pl.set_objectOfResponse(_res);
                            pl.notify();
                        }
                        break;
                    }
                }
            }
        }

        /* ZDP-BIND.Response */
        else if (_command == FreescaleConstants.ZDPMgmtBindResponse) {
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix("Extracted ZDP-BIND.Response", message);

            synchronized (listLocker) {
                for (ParserLocker pl : listLocker) {
                    if ((pl.getType() == TypeMessage.ADD_BINDING)) {
                        synchronized (pl) {
                            pl.getStatus().setCode(message[3]);
                            switch (pl.getStatus().getCode()) {
                            case GatewayConstants.SUCCESS:

                                break;

                            case 0x84:
                                pl.getStatus().setMessage("NOT_SUPPORTED (NOT SUPPORTED)");
                                break;

                            case 0x8C:
                                pl.getStatus().setMessage("TABLE_FULL (TABLE FULL)");
                                break;
                            case 0x8D:
                                pl.getStatus().setMessage("NOT_AUTHORIZED (NOT AUTHORIZED)");
                                break;
                            }
                            pl.notify();
                        }
                        break;
                    }
                }
            }
        }

        /* ZDP-UNBIND.Response */
        else if (_command == FreescaleConstants.ZDPUnbindResponse) {
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix("Extracted ZDP-UNBIND.Response", message);

            synchronized (listLocker) {
                for (ParserLocker pl : listLocker) {
                    if ((pl.getType() == TypeMessage.REMOVE_BINDING)) {
                        synchronized (pl) {
                            pl.getStatus().setCode(message[3]);
                            switch (pl.getStatus().getCode()) {
                            case GatewayConstants.SUCCESS:

                                break;

                            case 0x84:
                                pl.getStatus().setMessage("NOT_SUPPORTED (NOT SUPPORTED)");
                                break;
                            case 0x88:
                                pl.getStatus().setMessage("No_Entry (No Entry)");
                                break;
                            case 0x8D:
                                pl.getStatus().setMessage("NOT_AUTHORIZED (NOT AUTHORIZED");
                                break;
                            }
                            pl.notify();
                        }
                        break;
                    }
                }
            }
        }

        /* ZDP-Mgmt_Bind.Response */
        else if (_command == FreescaleConstants.ZDPMgmt_BindResponse) {
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix("Extracted ZDP-Mgmt_Bind.Response", message);

            synchronized (listLocker) {
                for (ParserLocker pl : listLocker) {
                    if ((pl.getType() == TypeMessage.GET_BINDINGS)) {
                        synchronized (pl) {
                            pl.getStatus().setCode(message[3]);
                            BindingList _res = new BindingList();

                            if (pl.getStatus().getCode() == GatewayConstants.SUCCESS) {
                                short length = message[6];
                                int _index = 6;
                                for (int i = 0; i < length; i++) {
                                    Binding _b = new Binding();
                                    long src_longAddress = DataManipulation.toLong((byte) message[_index + 8],
                                            (byte) message[_index + 7], (byte) message[_index + 6],
                                            (byte) message[_index + 5], (byte) message[_index + 4],
                                            (byte) message[_index + 3], (byte) message[_index + 2],
                                            (byte) message[_index + 1]);
                                    short _srcEP = message[_index + 9];

                                    int _cluster = DataManipulation.toIntFromShort((byte) message[_index + 11],
                                            (byte) message[_index + 10]);

                                    short _DestinationMode = message[_index + 12];
                                    Device _dev = new Device();

                                    if (_DestinationMode == 0x03) {

                                        long dst_longAddress = DataManipulation.toLong(
                                                (byte) message[_index + 20], (byte) message[_index + 19],
                                                (byte) message[_index + 18], (byte) message[_index + 17],
                                                (byte) message[_index + 16], (byte) message[_index + 15],
                                                (byte) message[_index + 14], (byte) message[_index + 13]);

                                        short _dstEP = message[_index + 21];
                                        _dev.setAddress(BigInteger.valueOf(dst_longAddress));
                                        _dev.setEndpoint(_dstEP);
                                        _index = _index + 21;
                                    } else if (_DestinationMode == 0x01) {

                                        int _groupId = DataManipulation.toIntFromShort(
                                                (byte) message[_index + 14], (byte) message[_index + 13]);
                                        _dev.setAddress(BigInteger.valueOf(_groupId));
                                        _index = _index + 10;
                                    }
                                    _b.setClusterID(_cluster);
                                    _b.setSourceEndpoint(_srcEP);
                                    _b.setSourceIEEEAddress(BigInteger.valueOf(src_longAddress));

                                    _b.getDeviceDestination().add(_dev);
                                    _res.getBinding().add(_b);

                                }
                            }
                            pl.set_objectOfResponse(_res);
                            pl.notify();
                        }
                        break;
                    }
                }
            }
        }

        /* APS-DeregisterEndPoint.Confirm */
        else if (_command == FreescaleConstants.APSDeRegisterEndPointConfirm) {
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix("Extracted APS-DeregisterEndPoint.Confirm", message);
            synchronized (listLocker) {
                for (ParserLocker pl : listLocker) {
                    if ((pl.getType() == TypeMessage.DEREGISTER_END_POINT)) {
                        synchronized (pl) {
                            pl.getStatus().setCode(message[3]);
                            pl.notify();
                        }
                        break;
                    }
                }
            }

        }

        /* APS-ZDP-Mgmt_Lqi.Response */
        else if (_command == FreescaleConstants.ZDPMgmtLqiResponse) {
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix(
                        "Extracted ZDP-Mgmt_Lqi.Response... waiting the related Indication ZDO", message);

        }
        /* ZTC-ReadExtAddr.Confirm */
        else if (_command == FreescaleConstants.ZTCReadExtAddrConfirm) {
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix("Extracted ZTC-ReadExtAddr.Confirm", message);
            long longAddress = DataManipulation.toLong((byte) message[11], (byte) message[10],
                    (byte) message[9], (byte) message[8], (byte) message[7], (byte) message[6],
                    (byte) message[5], (byte) message[4]);
            BigInteger _bi = BigInteger.valueOf(longAddress);
            synchronized (listLocker) {
                for (ParserLocker pl : listLocker) {
                    if ((pl.getType() == TypeMessage.READ_EXT_ADDRESS)) {
                        synchronized (pl) {
                            pl.set_objectOfResponse(_bi);
                            pl.getStatus().setCode(message[3]);
                            pl.notify();
                        }
                        break;
                    }
                }
            }

        }

        /* ZDP-IEEE_addr.response */
        else if (_command == FreescaleConstants.ZDPIeeeAddrResponse) {
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix("Extracted ZDP-IEEE_addr.response", message);
            long longAddress = DataManipulation.toLong((byte) message[11], (byte) message[10],
                    (byte) message[9], (byte) message[8], (byte) message[7], (byte) message[6],
                    (byte) message[5], (byte) message[4]);
            BigInteger _bi = BigInteger.valueOf(longAddress);
            synchronized (listLocker) {
                for (ParserLocker pl : listLocker) {
                    if ((pl.getType() == TypeMessage.READ_IEEE_ADDRESS)) {
                        synchronized (pl) {
                            pl.set_objectOfResponse(_bi);
                            pl.getStatus().setCode(message[3]);
                            pl.notify();
                        }
                        break;
                    }
                }
            }

        }
        /* ZDP-Mgmt_Leave.Response */
        else if (_command == FreescaleConstants.ZDPMgmtLeaveResponse) {
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix("Extracted ZDP-Mgmt_Leave.Response", message);

        }
        /* ZDP-Active_EP_rsp.response */
        else if (_command == FreescaleConstants.ZDPActiveEpResponse) {
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix("Extracted ZDP-Active_EP_rsp.response", message);
            short Status = message[3];
            Address _add = new Address();

            _add.setNetworkAddress(DataManipulation.toIntFromShort((byte) message[5], (byte) message[4]));
            String Key = String.format("%04X", _add.getNetworkAddress());
            List<Short> _toRes = null;

            NodeServices _node = new NodeServices();
            _node.setAddress(_add);

            switch (Status) {
            case 0x00:
                _toRes = new ArrayList<Short>();
                int _EPCount = message[6];

                for (int i = 0; i < _EPCount; i++) {
                    _toRes.add(message[7 + i]);
                    ActiveEndpoints _aep = new ActiveEndpoints();
                    _aep.setEndPoint(message[7 + i]);
                    _node.getActiveEndpoints().add(_aep);

                }
                if (gal.getPropertiesManager().getDebugEnabled()) {
                    logger.info("ZDP-Active_EP_rsp.response status:00 - Success");
                }
                break;
            case 0x80:
                if (gal.getPropertiesManager().getDebugEnabled()) {
                    logger.info("ZDP-Active_EP_rsp.response status:80 - Inv_RequestType");
                }
                break;
            case 0x89:
                if (gal.getPropertiesManager().getDebugEnabled()) {
                    logger.info("ZDP-Active_EP_rsp.response status:89 - No_Descriptor");
                }
                break;
            case 0x81:
                if (gal.getPropertiesManager().getDebugEnabled()) {
                    logger.info("ZDP-Active_EP_rsp.response status:81 - Device_Not_found");
                }
                break;
            }
            // Found ZDP-Active_EP_rsp.response. Remove the lock
            synchronized (listLocker) {
                for (ParserLocker pl : listLocker) {
                    /* DestAddress */
                    if ((pl.getType() == TypeMessage.ACTIVE_EP) && pl.get_Key().equalsIgnoreCase(Key)) {
                        synchronized (pl) {
                            pl.set_objectOfResponse(_toRes);
                            pl.getStatus().setCode(Status);
                            pl.notify();

                        }
                        break;
                    }
                }
            }

        }

        /* ZDP-StopNwkEx.Confirm */
        else if (_command == FreescaleConstants.ZTCStopNwkExConfirm) {
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix("Extracted ZDP-StopNwkEx.Confirm", message);
            synchronized (listLocker) {
                for (ParserLocker pl : listLocker) {
                    if (pl.getType() == TypeMessage.STOP_NETWORK) {
                        if (message[3] == 0x00) {
                            gal.get_gatewayEventManager().notifyGatewayStopResult(makeStatusObject(
                                    "The stop command has been processed byt ZDO with success.", (short) 0x00));
                            synchronized (gal) {
                                gal.setGatewayStatus(GatewayStatus.GW_STOPPING);
                            }
                        }
                        synchronized (pl) {
                            pl.getStatus().setCode(message[3]);
                            pl.notify();
                        }
                        break;
                    }
                }
            }

        }
        /* NLME-GET.Confirm */
        else if (_command == FreescaleConstants.NLMEGetConfirm) {
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix("Extracted NLME-GET.Confirm", message);
            String _Key = String.format("%02X", message[4]);
            // Found APSDE-DATA.Confirm. Remove the lock
            synchronized (listLocker) {
                for (ParserLocker pl : listLocker) {
                    if (pl.getType() == TypeMessage.NMLE_GET && pl.get_Key().equalsIgnoreCase(_Key)) {
                        short _Length = (short) DataManipulation.toIntFromShort((byte) message[9],
                                (byte) message[8]);
                        byte[] _res = DataManipulation.subByteArray(message, 10, _Length + 9);
                        if (_Length >= 2)
                            _res = DataManipulation.reverseBytes(_res);
                        synchronized (pl) {
                            pl.getStatus().setCode(message[3]);
                            pl.set_objectOfResponse(DataManipulation.convertBytesToString(_res));
                            pl.notify();
                        }
                        break;
                    }
                }
            }

        }
        /* APSME_GET.Confirm */
        else if (_command == FreescaleConstants.APSMEGetConfirm) {
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix("Extracted APSME_GET.Confirm", message);
            String _Key = String.format("%02X", message[4]);
            // Found APSME_GET-DATA.Confirm. Remove the lock
            synchronized (listLocker) {
                for (ParserLocker pl : listLocker) {
                    if (pl.getType() == TypeMessage.APSME_GET && pl.get_Key().equalsIgnoreCase(_Key)) {
                        short _Length = (short) DataManipulation.toIntFromShort((byte) message[9],
                                (byte) message[8]);
                        byte[] _res = DataManipulation.subByteArray(message, 10, _Length + 9);
                        if (_Length >= 2)
                            _res = DataManipulation.reverseBytes(_res);
                        synchronized (pl) {
                            pl.getStatus().setCode(message[3]);
                            pl.set_objectOfResponse(DataManipulation.convertBytesToString(_res));
                            pl.notify();
                        }
                        break;
                    }
                }
            }

        }
        // ZDP-StartNwkEx.Confirm
        else if (_command == FreescaleConstants.ZTCStartNwkExConfirm) {
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix("Extracted ZDP-StartNwkEx.Confirm", message);
            synchronized (listLocker) {
                for (ParserLocker pl : listLocker) {
                    if (pl.getType() == TypeMessage.START_NETWORK) {
                        if (message[3] == 0x00) {
                            gal.setGatewayStatus(GatewayStatus.GW_STARTED);
                        }
                        synchronized (pl) {
                            pl.getStatus().setCode(message[3]);
                            pl.notify();
                        }
                        break;
                    }
                }
            }
        }

        /* APS-RegisterEndPoint.Confirm */
        else if (_command == FreescaleConstants.APSRegisterEndPointConfirm) {
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix("Extracted APS-RegisterEndPoint.Confirm", message);
            // Found APS-RegisterEndPoint.Confirm. Remove the lock
            synchronized (listLocker) {
                for (ParserLocker pl : listLocker) {
                    if (pl.getType() == TypeMessage.CONFIGURE_END_POINT) {
                        synchronized (pl) {
                            pl.getStatus().setCode(message[3]);
                            pl.notify();
                        }
                        break;
                    }
                }
            }
        }
        /* ZTC-ModeSelect.Confirm */
        else if (_command == FreescaleConstants.ZTCModeSelectConfirm) {
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix("Extracted ZTC-ModeSelect.Confirm", message);
            short status = message[3];
            synchronized (listLocker) {
                for (ParserLocker pl : listLocker) {
                    if (pl.getType() == TypeMessage.MODE_SELECT) {
                        synchronized (pl) {
                            pl.getStatus().setCode(status);
                            pl.notify();
                        }
                        break;
                    }
                }
            }
        }
        /* MacGetPIBAttribute.Confirm */
        else if (_command == FreescaleConstants.MacGetPIBAttributeConfirm) {
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix("Extracted MacGetPIBAttribute.Confirm", message);
        }
        /* MacBeaconNotify.Indication */
        else if (_command == FreescaleConstants.MacBeaconNotifyIndication) {
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix("Extracted MacBeaconNotify.Indication", message);
        }
        /* MacBeaconStart.Indication */
        else if (_command == FreescaleConstants.MacPollNotifyIndication) {
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix("Extracted MacBeaconStart.Indication", message);
        }
        /* NLME-NETWORK-FORMATION.Confirmn */
        else if (_command == FreescaleConstants.NLMENETWORKFORMATIONConfirm) {
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix("Extracted NLME-NETWORK-FORMATION.Confirm", message);
        }
        /* NLME-START-ROUTER.Request */
        else if (_command == FreescaleConstants.NLMESTARTROUTERRequest) {
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix("Extracted NLME-NETWORK-FORMATION.Confirm", message);
        }
        /* MacStart.Request */
        else if (_command == FreescaleConstants.MacStartRequest) {
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix("Extracted MacStart.Request", message);
        }
        /* MacStart.Confirm */
        else if (_command == FreescaleConstants.MacStartConfirm) {
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix("Extracted MacStart.Confirm", message);
        }
        /* NLME-START-ROUTER.Confirm */
        else if (_command == FreescaleConstants.NLMESTARTROUTERConfirm) {
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix("Extracted NLME-START-ROUTER.Confirm", message);
        }
        /* NWK-ProcessSecureFrame.Report */
        else if (_command == FreescaleConstants.NWKProcessSecureFrameReport) {
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix("Extracted NWK-ProcessSecureFrame.Report", message);
        }
        /* ZDP-Nwk-ProcessSecureFrame.Confirm */
        else if (_command == FreescaleConstants.ZDPNwkProcessSecureFrameConfirm) {
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix("Extracted ZDP-Nwk-ProcessSecureFrame.Confirm", message);
        }

        /* BlackBox.WriteSAS.Confirm */
        else if (_command == FreescaleConstants.BlackBoxWriteSASConfirm) {
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix("Extracted BlackBox.WriteSAS.Confirm", message);
            synchronized (listLocker) {
                for (ParserLocker pl : listLocker) {
                    if (pl.getType() == TypeMessage.WRITE_SAS) {
                        synchronized (pl) {
                            pl.getStatus().setCode(message[3]);
                            pl.notify();
                        }
                        break;
                    }
                }
            }
        }
        /* ZTC-GetChannel.Confirm */
        else if (_command == FreescaleConstants.ZTCGetChannelConfirm) {
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix("Extracted ZTC-GetChannel.Confirm", message);
            synchronized (listLocker) {
                for (ParserLocker pl : listLocker) {
                    if (pl.getType() == TypeMessage.CHANNEL_REQUEST) {
                        synchronized (pl) {
                            pl.getStatus().setCode(message[3]);
                            pl.set_objectOfResponse(message[4]);
                            pl.notify();
                        }
                        break;
                    }
                }
            }
        }

        /* ZDP-NodeDescriptor.Response */
        else if (_command == FreescaleConstants.ZDPNodeDescriptorResponse) {
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix("Extracted ZDP-NodeDescriptor.Response", message);
            int _NWKAddressOfInterest = DataManipulation.toIntFromShort((byte) message[5], (byte) message[4]);
            Address _addressOfInterst = new Address();
            _addressOfInterst.setNetworkAddress(_NWKAddressOfInterest);
            NodeDescriptor _node = new NodeDescriptor();

            /* First Byte */
            byte _first = (byte) message[6];
            byte _Logical_byte = (byte) (_first & 0x07);/* Bits 0,1,2 */
            byte _ComplexDescriptorAvalilable = (byte) ((_first & 0x08) >> 3);/* Bit3 */
            byte _UserDescriptorAvalilable = (byte) ((_first & 0x0A) >> 4);/* Bit4 */
            switch (_Logical_byte) {
            case FreescaleConstants.LogicalType.Coordinator:
                _node.setLogicalType(LogicalType.COORDINATOR);
                break;
            case FreescaleConstants.LogicalType.Router:
                _node.setLogicalType(LogicalType.ROUTER);
                break;
            case FreescaleConstants.LogicalType.EndDevice:
                _node.setLogicalType(LogicalType.END_DEVICE);
                break;
            default:
                throw new Exception("LogicalType is not valid value");
            }
            _node.setComplexDescriptorAvailable((_ComplexDescriptorAvalilable == 1 ? true : false));
            _node.setUserDescriptorAvailable((_UserDescriptorAvalilable == 1 ? true : false));

            /* Second Byte */
            byte _second = (byte) message[7];
            /* Aps flags bits 0,1,2 */
            byte _FrequencyBand = (byte) ((_second & 0xF8) >> 0x03);/*
                                                                    * bits
                                                                    * 3
                                                                    * ,4,5,
                                                                    * 6,7
                                                                    */
            switch (_FrequencyBand) {
            case 0x01:
                _node.setFrequencyBand("868MHz");
                break;
            case 0x04:
                _node.setFrequencyBand("900MHz");
                break;
            case 0x08:
                _node.setFrequencyBand("2400MHz");
                break;
            default:
                _node.setFrequencyBand("Reserved");
                break;
            }

            /* MACcapabilityFlags_BYTE Byte */
            byte _MACcapabilityFlags_BYTE = (byte) message[8];
            MACCapability _maccapability = new MACCapability();
            byte _AlternatePanCoordinator = (byte) (_MACcapabilityFlags_BYTE & 0x01);/* Bit0 */
            byte _DeviceIsFFD = (byte) ((_MACcapabilityFlags_BYTE & 0x02) >> 1);/* Bit1 */
            byte _MainsPowered = (byte) ((_MACcapabilityFlags_BYTE & 0x04) >> 2);/* Bit2 */
            byte _ReceiverOnWhenIdle = (byte) ((_MACcapabilityFlags_BYTE & 0x08) >> 3);/* Bit3 */
            // bit 4-5 reserved
            byte _SecuritySupported = (byte) ((_MACcapabilityFlags_BYTE & 0x40) >> 6);/* Bit6 */
            byte _AllocateAddress = (byte) ((_MACcapabilityFlags_BYTE & 0x80) >> 7);/* Bit7 */
            _maccapability.setAlternatePanCoordinator((_AlternatePanCoordinator == 1 ? true : false));
            _maccapability.setDeviceIsFFD((_DeviceIsFFD == 1 ? true : false));
            _maccapability.setMainsPowered((_MainsPowered == 1 ? true : false));
            _maccapability.setReceiverOnWhenIdle((_ReceiverOnWhenIdle == 1 ? true : false));
            _maccapability.setSecuritySupported((_SecuritySupported == 1 ? true : false));
            _maccapability.setAllocateAddress((_AllocateAddress == 1 ? true : false));
            _node.setMACCapabilityFlag(_maccapability);

            /* ManufacturerCode_BYTES */
            int _ManufacturerCode_BYTES = DataManipulation.toIntFromShort((byte) message[10],
                    (byte) message[9]);
            _node.setManufacturerCode(_ManufacturerCode_BYTES);

            /* MaximumBufferSize_BYTE */
            short _MaximumBufferSize_BYTE = message[11];
            _node.setMaximumBufferSize(_MaximumBufferSize_BYTE);

            /* MaximumTransferSize_BYTES */
            int _MaximumTransferSize_BYTES = DataManipulation.toIntFromShort((byte) message[13],
                    (byte) message[12]);
            _node.setMaximumIncomingTransferSize(_MaximumTransferSize_BYTES);

            /* ServerMask_BYTES */
            int _ServerMask_BYTES = DataManipulation.toIntFromShort((byte) message[15], (byte) message[14]);
            ServerMask _serverMask = new ServerMask();
            byte _PrimaryTrustCenter = (byte) (_ServerMask_BYTES & 0x01);/* Bit0 */
            byte _BackupTrustCenter = (byte) ((_ServerMask_BYTES & 0x02) >> 1);/* Bit1 */
            byte _PrimaryBindingTableCache = (byte) ((_ServerMask_BYTES & 0x04) >> 2);/* Bit2 */
            byte _BackupBindingTableCache = (byte) ((_ServerMask_BYTES & 0x08) >> 3);/* Bit3 */
            byte _PrimaryDiscoveryCache = (byte) ((_ServerMask_BYTES & 0x10) >> 4);/* Bit4 */
            byte _BackupDiscoveryCache = (byte) ((_ServerMask_BYTES & 0x20) >> 5);/* Bit5 */
            _serverMask.setPrimaryTrustCenter((_PrimaryTrustCenter == 1 ? true : false));
            _serverMask.setBackupTrustCenter((_BackupTrustCenter == 1 ? true : false));
            _serverMask.setPrimaryBindingTableCache((_PrimaryBindingTableCache == 1 ? true : false));
            _serverMask.setBackupBindingTableCache((_BackupBindingTableCache == 1 ? true : false));
            _serverMask.setPrimaryDiscoveryCache((_PrimaryDiscoveryCache == 1 ? true : false));
            _serverMask.setBackupDiscoveryCache((_BackupDiscoveryCache == 1 ? true : false));
            _node.setServerMask(_serverMask);

            /* MaximumOutTransferSize_BYTES */
            int _MaximumOutTransferSize_BYTES = DataManipulation.toIntFromShort((byte) message[17],
                    (byte) message[16]);
            _node.setMaximumOutgoingTransferSize(_MaximumOutTransferSize_BYTES);

            /* CapabilityField_BYTES */
            byte _CapabilityField_BYTES = (byte) message[18];
            DescriptorCapability _DescriptorCapability = new DescriptorCapability();
            byte _ExtendedActiveEndpointListAvailable = (byte) (_CapabilityField_BYTES & 0x01);/* Bit0 */
            byte _ExtendedSimpleDescriptorListAvailable = (byte) ((_CapabilityField_BYTES
                    & 0x02) >> 1);/* Bit1 */
            _DescriptorCapability.setExtendedActiveEndpointListAvailable(
                    (_ExtendedActiveEndpointListAvailable == 1 ? true : false));
            _DescriptorCapability.setExtendedSimpleDescriptorListAvailable(
                    (_ExtendedSimpleDescriptorListAvailable == 1 ? true : false));
            _node.setDescriptorCapabilityField(_DescriptorCapability);
            String _key = String.format("%04X", _NWKAddressOfInterest);
            synchronized (listLocker) {
                for (ParserLocker pl : listLocker) {
                    if (pl.getType() == TypeMessage.NODE_DESCRIPTOR && pl.get_Key().equalsIgnoreCase(_key)) {
                        synchronized (pl) {
                            pl.getStatus().setCode(message[3]);/* Status */
                            pl.set_objectOfResponse(_node);
                            pl.notify();
                        }
                        break;
                    }
                }
            }
        }
        /* NMLE-SET.Confirm */
        else if (_command == FreescaleConstants.NMLESETConfirm) {
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix("Extracted NMLE-SET.Confirm", message);
            short status = message[3];
            synchronized (listLocker) {
                for (ParserLocker pl : listLocker) {
                    if (pl.getType() == TypeMessage.NMLE_SET) {

                        synchronized (pl) {
                            pl.getStatus().setCode(status);
                            pl.notify();
                        }
                        break;
                    }
                }
            }
        }
        /* APSME-SET.Confirm */
        else if (_command == FreescaleConstants.APSMESetConfirm) {
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix("Extracted APSME-SET.Confirm", message);
            short status = message[3];
            synchronized (listLocker) {
                for (ParserLocker pl : listLocker) {
                    if (pl.getType() == TypeMessage.APSME_SET) {

                        synchronized (pl) {
                            pl.getStatus().setCode(status);
                            pl.notify();
                        }
                        break;
                    }
                }
            }
        }

        /* ZDP-Mgmt_Permit_Join.response */
        else if (_command == FreescaleConstants.ZDPMgmt_Permit_JoinResponse) {
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix("Extracted ZDP-Mgmt_Permit_Join.response", message);
            short status = message[3];
            String mess = "";

            switch (status) {
            case 0x00:

                break;
            case 0x80:
                mess = "InvRequestType";
                break;
            case 0x84:
                mess = "Not Supported";
                break;
            case 0x87:
                mess = "Table Full";
                break;
            case 0x8D:
                mess = "NOT AUTHORIZED";
                break;
            case 0xC5:
                mess = "Already present in the network";
                break;

            }
            synchronized (listLocker) {
                for (ParserLocker pl : listLocker) {
                    if (pl.getType() == TypeMessage.PERMIT_JOIN) {
                        synchronized (pl) {
                            pl.getStatus().setCode(status);
                            pl.getStatus().setMessage(mess);
                            pl.notify();
                        }
                        break;
                    }
                }

            }
        }

        /* APS-ClearDeviceKeyPairSet.Confirm */
        else if (_command == FreescaleConstants.APSClearDeviceKeyPairSetConfirm) {
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix("APS-ClearDeviceKeyPairSet.Confirm", message);
            short status = message[3];
            String mess = "";
            switch (status) {
            case 0x00:

                break;
            }
            synchronized (listLocker) {
                for (ParserLocker pl : listLocker) {
                    if (pl.getType() == TypeMessage.CLEAR_DEVICE_KEY_PAIR_SET) {
                        synchronized (pl) {
                            pl.getStatus().setCode(status);
                            pl.getStatus().setMessage(mess);
                            pl.notify();
                        }
                        break;
                    }
                }

            }

        }

        /* ZTC-ClearNeighborTableEntry.Confirm */
        else if (_command == FreescaleConstants.ZTCClearNeighborTableEntryConfirm) {
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix("ZTC-ClearNeighborTableEntry.Confirm", message);
            short status = message[3];
            String mess = "";
            switch (status) {
            case 0x00:

                break;
            }
            synchronized (listLocker) {
                for (ParserLocker pl : listLocker) {
                    if (pl.getType() == TypeMessage.CLEAR_NEIGHBOR_TABLE_ENTRY) {
                        synchronized (pl) {
                            pl.getStatus().setCode(status);
                            pl.getStatus().setMessage(mess);
                            pl.notify();
                        }
                        break;
                    }
                }

            }

        }

        /* NLME-JOIN.Confirm */
        else if (_command == FreescaleConstants.NLMEJOINConfirm) {
            short _status = message[8];
            switch (_status) {
            case 0x00:
                if (gal.getPropertiesManager().getDebugEnabled()) {
                    logger.info("Extracted NLME-JOIN.Confirm: SUCCESS (Joined the network)");
                }
                break;
            case 0xC2:
                if (gal.getPropertiesManager().getDebugEnabled()) {
                    logger.info("Extracted NLME-JOIN.Confirm: INVALID_REQUEST (Not Valid Request)");
                }
                break;
            case 0xC3:
                if (gal.getPropertiesManager().getDebugEnabled()) {
                    logger.info("Extracted NLME-JOIN.Confirm: NOT_PERMITTED (Not allowed to join the network)");
                }
                break;
            case 0xCA:
                if (gal.getPropertiesManager().getDebugEnabled()) {
                    logger.info("Extracted NLME-JOIN.Confirm: NO_NETWORKS (Network not found)");
                }
                break;
            case 0x01:
                if (gal.getPropertiesManager().getDebugEnabled()) {
                    logger.info("Extracted NLME-JOIN.Confirm: PAN_AT_CAPACITY (PAN at capacity)");
                }
                break;
            case 0x02:
                if (gal.getPropertiesManager().getDebugEnabled()) {
                    logger.info("Extracted NLME-JOIN.Confirm: PAN_ACCESS_DENIED (PAN access denied)");
                }
                break;
            case 0xE1:
                if (gal.getPropertiesManager().getDebugEnabled()) {
                    logger.info(
                            "Extracted NLME-JOIN.Confirm: CHANNEL_ACCESS_FAILURE (Transmission failed due to activity on the channel)");
                }
                break;
            case 0xE4:
                if (gal.getPropertiesManager().getDebugEnabled()) {
                    logger.info(
                            "Extracted NLME-JOIN.Confirm: FAILED_SECURITY_CHECK (The received frame failed security check)");
                }
                break;
            case 0xE8:
                if (gal.getPropertiesManager().getDebugEnabled()) {
                    logger.info(
                            "Extracted NLME-JOIN.Confirm: INVALID_PARAMETER (A parameter in the primitive is out of the valid range)");
                }
                break;
            case 0xE9:
                if (gal.getPropertiesManager().getDebugEnabled()) {
                    logger.info("Extracted NLME-JOIN.Confirm: NO_ACK (Acknowledgement was not received)");
                }
                break;
            case 0xEB:
                if (gal.getPropertiesManager().getDebugEnabled()) {
                    logger.info(
                            "Extracted NLME-JOIN.Confirm: NO_DATA (No response data was available following a request)");
                }
                break;
            case 0xF3:
                if (gal.getPropertiesManager().getDebugEnabled()) {
                    logger.info(
                            "Extracted NLME-JOIN.Confirm: UNAVAILABLE_KEY (The appropriate key is not available in the ACL)");
                }
                break;
            case 0xEA:
                if (gal.getPropertiesManager().getDebugEnabled()) {
                    logger.info("Extracted NLME-JOIN.Confirm: NO_BEACON (No Networks)");
                }
                break;
            default:
                throw new Exception("Extracted NLME-JOIN.Confirm: Invalid Status - " + _status);
            }
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix("NLME-JOIN.Confirm", message);
        }

        /* ZDO-NetworkState.Event */
        else if (_command == FreescaleConstants.ZDONetworkStateEvent) {
            short _status = message[3];
            String mess;
            switch (_status) {
            case 0x00:
                if (gal.getPropertiesManager().getDebugEnabled()) {
                    logger.info("Extracted ZDO-NetworkState.Event: DeviceInitialized (Device Initialized)");
                }
                break;
            case 0x01:
                if (gal.getPropertiesManager().getDebugEnabled()) {
                    logger.info(
                            "Extracted ZDO-NetworkState.Event: DeviceinNetworkDiscoveryState (Device in Network Discovery State)");
                }
                break;
            case 0x02:
                if (gal.getPropertiesManager().getDebugEnabled()) {
                    logger.info(
                            "Extracted ZDO-NetworkState.Event: DeviceJoinNetworkstate (Device Join Network state)");
                }
                break;
            case 0x03:
                if (gal.getPropertiesManager().getDebugEnabled()) {
                    logger.info(
                            "Extracted ZDO-NetworkState.Event: DeviceinCoordinatorstartingstate (Device in Coordinator starting state)");
                }
                gal.setGatewayStatus(GatewayStatus.GW_STARTING);
                break;
            case 0x04:
                mess = "ZDO-NetworkState.Event: DeviceinRouterRunningstate (Device in Router Running state)";
                gal.get_gatewayEventManager().notifyGatewayStartResult(makeStatusObject(mess, _status));
                gal.setGatewayStatus(GatewayStatus.GW_RUNNING);
                if (gal.getPropertiesManager().getDebugEnabled()) {
                    logger.info(mess);
                }
                break;
            case 0x05:
                mess = "ZDO-NetworkState.Event: DeviceinEndDeviceRunningstate (Device in End Device Running state)";
                gal.get_gatewayEventManager().notifyGatewayStartResult(makeStatusObject(mess, _status));
                gal.setGatewayStatus(GatewayStatus.GW_RUNNING);

                if (gal.getPropertiesManager().getDebugEnabled()) {
                    logger.info(mess);
                }
                break;
            case 0x09:
                if (gal.getPropertiesManager().getDebugEnabled()) {
                    logger.info(
                            "Extracted ZDO-NetworkState.Event: Deviceinleavenetworkstate (Device in leave network state)");
                }

                gal.setGatewayStatus(GatewayStatus.GW_STOPPING);
                break;
            case 0x0A:
                if (gal.getPropertiesManager().getDebugEnabled()) {
                    logger.info(
                            "Extracted ZDO-NetworkState.Event: Deviceinauthenticationstate (Device in authentication state)");
                }
                break;
            case 0x0B:
                if (gal.getPropertiesManager().getDebugEnabled()) {
                    logger.info(
                            "Extracted ZDO-NetworkState.Event: Deviceinstoppedstate (Device in stopped state)");
                }
                gal.setGatewayStatus(GatewayStatus.GW_STOPPED);

                break;
            case 0x0C:
                if (gal.getPropertiesManager().getDebugEnabled()) {
                    logger.info(
                            "Extracted ZDO-NetworkState.Event: DeviceinOrphanjoinstate (Device in Orphan join state)");
                }
                break;
            case 0x10:
                mess = "ZDO-NetworkState.Event: DeviceinCoordinatorRunningstate (Device is Coordinator Running state)";

                gal.get_gatewayEventManager().notifyGatewayStartResult(makeStatusObject(mess, _status));
                gal.setGatewayStatus(GatewayStatus.GW_RUNNING);
                if (gal.getPropertiesManager().getDebugEnabled()) {
                    logger.info(mess);
                }
                break;
            case 0x11:
                if (gal.getPropertiesManager().getDebugEnabled()) {
                    logger.info(
                            "Extracted ZDO-NetworkState.Event: DeviceinKeytransferstate (Device in Key transfer state)");
                }
                break;
            case 0x12:
                if (gal.getPropertiesManager().getDebugEnabled()) {
                    logger.info(
                            "Extracted ZDO-NetworkState.Event: Deviceinauthenticationstate (Device in authentication state)");
                }
                break;
            case 0x13:
                if (gal.getPropertiesManager().getDebugEnabled()) {
                    logger.info(
                            "Extracted ZDO-NetworkState.Event: DeviceOfftheNetwork (Device Off the Network)");
                }
                break;
            default:
                throw new Exception("ZDO-NetworkState.Event: Invalid Status - " + _status);
            }
        }
        /* MacSetPIBAttribute.Confirm */
        else if (_command == FreescaleConstants.MacSetPIBAttributeConfirm) {
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix("Extracted MacSetPIBAttribute.Confirm", message);
        }
        /* NLME-ENERGY-SCAN.Request */
        else if (_command == FreescaleConstants.NLMEENERGYSCANRequest) {
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix("Extracted NLME-ENERGY-SCAN.Request", message);
        }
        /* MacScan.Request */
        else if (_command == FreescaleConstants.MacScanRequest) {
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix("Extracted MacScan.Request", message);
        }
        /* MacScan.Confirm */
        else if (_command == FreescaleConstants.MacScanConfirm) {
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix("Extracted MacScan.Confirm", message);
        }
        /* NLME-ENERGY-SCAN.confirm */
        else if (_command == FreescaleConstants.NLMEENERGYSCANconfirm) {
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix("Extracted NLME-ENERGY-SCAN.confirm", message);
        }
        /* NLME-NETWORK-DISCOVERY.Request */
        else if (_command == FreescaleConstants.NLMENETWORKDISCOVERYRequest) {
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix("Extracted NLME-NETWORK-DISCOVERY.Request", message);
        }
        /* MacScan.Request */
        else if (_command == FreescaleConstants.MacScanRequest) {
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix("Extracted MacScan.Request", message);
        }
        /* NLME-NETWORK-DISCOVERY.Confirm */
        else if (_command == FreescaleConstants.NLMENetworkDiscoveryConfirm) {
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix("Extracted NLME-NETWORK-DISCOVERY.Confirm", message);
        }
        /* NLME-NETWORK-FORMATION.Request */
        else if (_command == FreescaleConstants.NLMENETWORKFORMATIONRequest) {
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix("Extracted NLME-NETWORK-FORMATION.Request", message);
        }
        /* NLME-SET.Request */
        else if (_command == FreescaleConstants.NLMESetRequest) {
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix("Extracted NLME-SET.Request", message);
        }
        /* NLME-NWK-STATUS.Indication */
        else if (_command == FreescaleConstants.NLMENwkStatusIndication) {
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix("NLME-NWK-STATUS.Indication", message);
        }
        /* NLME-ROUTE-DISCOVERY.confirm */
        else if (_command == FreescaleConstants.NLMENWKSTATUSIndication) {
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix("NLME-ROUTE-DISCOVERY.confirm", message);
        } else {
            if (gal.getPropertiesManager().getDebugEnabled())
                DataManipulation.logArrayHexRadix("Extracted a Message not in Message Management", message);
        }

        synchronized (this) {
            _size = messages.size();
        }
    }

}

From source file:org.dasein.cloud.cloudsigma.compute.vm.ServerSupport.java

@Override
public @Nonnull VirtualMachine launch(@Nonnull VMLaunchOptions withLaunchOptions)
        throws CloudException, InternalException {
    logger.debug("Name: " + withLaunchOptions.getHostName() + ", description: "
            + withLaunchOptions.getDescription() + "friendly name: " + withLaunchOptions.getFriendlyName());
    if (logger.isTraceEnabled()) {
        logger.trace("ENTER - " + ServerSupport.class.getName() + ".launch(" + withLaunchOptions + ")");
    }//from w  w w . ja v  a  2s.c o m
    try {
        MachineImage img = provider.getComputeServices().getImageSupport()
                .getImage(withLaunchOptions.getMachineImageId());

        if (img == null) {
            throw new CloudException("No such machine image: " + withLaunchOptions.getMachineImageId());
        }

        MachineImageState state = img.getCurrentState();
        String name = img.getName();
        boolean cloneFound = false;
        if (state.equals(MachineImageState.ACTIVE) && name.contains("clone")) {
            logger.info("Available 'clone' - will attach directly to new server");
            cloneFound = true;
        } else {
            logger.info("Image is either mounted or is not a clone - cloning drive from machine image "
                    + img.getProviderMachineImageId());
        }

        String media = img.getTag("media").toString();

        String imageDriveId = null;
        //dmayne 20130529: cdrom does not need to be cloned and can be attached directly
        if (!media.equals("cdrom") && !cloneFound) {
            if (logger.isInfoEnabled()) {
                logger.info("Cloning drive from machine image " + img.getProviderMachineImageId() + "...");
            }

            JSONObject drive = provider.getComputeServices().getImageSupport()
                    .cloneDrive(withLaunchOptions.getMachineImageId(), withLaunchOptions.getHostName(), null);

            if (logger.isDebugEnabled()) {
                logger.debug("drive=" + drive);
            }
            String driveId = null;
            try {
                JSONObject actualDrive = null;
                if (drive.has("objects")) {
                    JSONArray objects = drive.getJSONArray("objects");
                    actualDrive = (JSONObject) objects.get(0);
                    driveId = actualDrive.getString("uuid");
                }

                if (driveId == null) {
                    throw new CloudException("No drive was cloned to support the machine launch process");
                }
                long timeout = System.currentTimeMillis() + (CalendarWrapper.MINUTE * 40L);
                String status = actualDrive.getString("status");

                if (logger.isInfoEnabled()) {
                    logger.info("Waiting for new drive " + driveId + " to become active...");
                }
                while (timeout > System.currentTimeMillis()) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("status.drive." + driveId + "=" + status);
                    }
                    if (status != null && (status.equals("mounted") || status.equals("unmounted"))) {
                        if (logger.isInfoEnabled()) {
                            logger.info("Drive is now ready for launching");
                        }
                        break;
                    }
                    try {
                        Thread.sleep(20000L);
                    } catch (InterruptedException ignore) {
                    }
                    try {
                        actualDrive = provider.getComputeServices().getImageSupport().getDrive(driveId);
                    } catch (Throwable ignore) {
                    }
                    if (actualDrive == null) {
                        throw new CloudException("Cloned drive has disappeared");
                    }
                    status = actualDrive.getString("status");
                }
                imageDriveId = actualDrive.getString("uuid");
            } catch (JSONException e) {
                throw new InternalException(e);
            }
        } else {
            imageDriveId = img.getProviderMachineImageId();
        }

        //dmayne 20130529: now we can create server and attach drive
        try {
            JSONObject newServer = new JSONObject(), newDrive = new JSONObject(), newNic = new JSONObject(),
                    newVlan = new JSONObject();
            JSONArray drives = new JSONArray(), nics = new JSONArray();

            newServer.put("name", withLaunchOptions.getHostName().replaceAll("\n", " "));
            String password = withLaunchOptions.getBootstrapPassword();

            if (password == null) {
                password = generatePassword();
            }
            newServer.put("vnc_password", password);

            newDrive.put("boot_order", 1);
            newDrive.put("device", "virtio");
            newDrive.put("dev_channel", "0:0");
            newDrive.put("drive", imageDriveId);

            drives.put(newDrive);

            newServer.put("drives", drives);

            String productId = withLaunchOptions.getStandardProductId();
            int cpuCount = 1, cpuSpeed = 1000, ramInMb = 512;
            long ramInBytes = 536870912;
            String[] parts = productId.replaceAll("\n", " ").split(":");
            if (parts.length > 1) {
                cpuCount = 1;
                try {
                    ramInMb = Integer.parseInt(parts[0]);
                    ramInBytes = ramInMb * 1024L * 1024L;
                    cpuSpeed = Integer.parseInt(parts[1]);
                    if (parts.length == 3) {
                        cpuCount = Integer.parseInt(parts[2]);
                        // total speed will be cpuCount * perSMPspeed
                        cpuSpeed = cpuSpeed * cpuCount;
                    }
                } catch (NumberFormatException ignore) {
                    // ignore
                }
            }

            newServer.put("cpu", String.valueOf(cpuSpeed));
            newServer.put("mem", String.valueOf(ramInBytes));
            newServer.put("smp", String.valueOf(cpuCount));

            if (withLaunchOptions.getVlanId() != null) {
                newVlan.put("uuid", withLaunchOptions.getVlanId().replaceAll("\n", " "));
                newNic.put("vlan", newVlan);
                nics.put(newNic);
                newServer.put("nics", nics);
            } else {
                JSONObject newIP = new JSONObject();
                newIP.put("conf", "dhcp");
                newNic.put("ip_v4_conf", newIP);

                //firewall support
                if (withLaunchOptions.getFirewallIds() != null
                        && withLaunchOptions.getFirewallIds().length > 0) {
                    if (withLaunchOptions.getFirewallIds().length == 1) {
                        newNic.put("firewall_policy", withLaunchOptions.getFirewallIds()[0]);
                    } else {
                        logger.warn(
                                "Firewall not applied to server as there is more than one - current list has "
                                        + withLaunchOptions.getFirewallIds().length);
                    }
                }

                nics.put(newNic);
                newServer.put("nics", nics);
            }

            CloudSigmaMethod method = new CloudSigmaMethod(provider);

            if (logger.isInfoEnabled()) {
                logger.info("Creating server....");
            }
            //dmayne 20130218: use JSON Parsing
            VirtualMachine vm = null;
            JSONObject obj = new JSONObject(method.postString("/servers/", newServer.toString()));

            //dmayne 20130227: check value returned and extract created server from the objects array
            if (obj != null) {
                JSONObject object = (JSONObject) obj;
                JSONArray arr = object.getJSONArray("objects");
                JSONObject server = arr.getJSONObject(0);
                vm = toVirtualMachine((JSONObject) server);
            }

            if (logger.isDebugEnabled()) {
                logger.debug("vm=" + vm);
            }
            if (vm == null) {
                throw new CloudException("No virtual machine was provided in the response");
            }
            if (logger.isInfoEnabled()) {
                logger.info("Waiting for " + vm.getProviderVirtualMachineId() + " to be STOPPED or RUNNING...");
            }
            vm = waitForState(vm, CalendarWrapper.MINUTE * 15L, VmState.STOPPED, VmState.RUNNING);
            if (logger.isDebugEnabled()) {
                logger.debug("post wait vm=" + vm);
            }
            if (vm == null) {
                throw new CloudException("Virtual machine disappeared waiting for startup state");
            }
            if (logger.isDebugEnabled()) {
                logger.debug("status.vm." + vm.getProviderVirtualMachineId() + "=" + vm.getCurrentState());
            }
            if (!VmState.RUNNING.equals(vm.getCurrentState())) {
                if (logger.isInfoEnabled()) {
                    logger.info("Setting up a separate thread to start " + vm.getProviderVirtualMachineId()
                            + "...");
                }
                final String id = vm.getProviderVirtualMachineId();

                Thread t = new Thread() {
                    public void run() {
                        try {
                            VirtualMachine vm = null;

                            for (int i = 0; i < 5; i++) {
                                try {
                                    if (vm == null) {
                                        try {
                                            vm = getVirtualMachine(id);
                                        } catch (Throwable ignore) {
                                            // ignore
                                        }
                                    }
                                    if (vm != null) {
                                        if (logger.isInfoEnabled()) {
                                            logger.info("Verifying the state of " + id);
                                        }
                                        vm = waitForState(vm, CalendarWrapper.MINUTE * 15L, VmState.STOPPED,
                                                VmState.RUNNING);
                                        if (vm == null || VmState.TERMINATED.equals(vm.getCurrentState())
                                                || VmState.RUNNING.equals(vm.getCurrentState())) {
                                            if (logger.isInfoEnabled()) {
                                                logger.info(
                                                        "Pre-emptive return due to non-existence or true running: "
                                                                + id);
                                            }
                                            return;
                                        }
                                    }
                                    if (logger.isInfoEnabled()) {
                                        logger.info("Start attempt " + (i + 1) + " on " + id);
                                    }
                                    ServerSupport.this.start(id);
                                    if (logger.isInfoEnabled()) {
                                        logger.info("VM " + id + " started");
                                    }
                                    try {
                                        Thread.sleep(2000L);
                                    } catch (InterruptedException ignore) {
                                    }
                                    return;
                                } catch (Exception e) {
                                    logger.warn("Failed to start virtual machine " + id + " post-create: "
                                            + e.getMessage());
                                }
                                try {
                                    Thread.sleep(60000L);
                                } catch (InterruptedException ignore) {
                                }
                            }
                            if (logger.isInfoEnabled()) {
                                logger.info("VM " + id + " never started");
                                if (vm != null) {
                                    logger.debug("status.vm." + id + " (not started)=" + vm.getCurrentState());
                                }
                            }
                        } finally {
                            provider.release();
                        }
                    }
                };

                provider.hold();
                t.setName("Start CloudSigma VM " + id);
                t.setDaemon(true);
                t.start();
            }
            return vm;
        }

        catch (JSONException e) {
            throw new InternalException(e);
        }
    } finally {
        if (logger.isTraceEnabled()) {
            logger.trace("EXIT - " + ServerSupport.class.getName() + ".launch()");
        }
    }
}

From source file:org.pentaho.di.trans.Trans.java

/**
 * Starts the threads prepared by prepareThreads(). Before you start the threads, you can add RowListeners to them.
 *
 * @throws KettleException//from  ww  w .j a va  2  s .co  m
 *           if there is a communication error with a remote output socket.
 */
public void startThreads() throws KettleException {
    // Now prepare to start all the threads...
    //
    nrOfFinishedSteps = 0;
    nrOfActiveSteps = 0;

    ExtensionPointHandler.callExtensionPoint(log, KettleExtensionPoint.TransformationStartThreads.id, this);

    fireTransStartedListeners();

    for (int i = 0; i < steps.size(); i++) {
        final StepMetaDataCombi sid = steps.get(i);
        sid.step.markStart();
        sid.step.initBeforeStart();

        // also attach a Step Listener to detect when we're done...
        //
        StepListener stepListener = new StepListener() {
            public void stepActive(Trans trans, StepMeta stepMeta, StepInterface step) {
                nrOfActiveSteps++;
                if (nrOfActiveSteps == 1) {
                    // Transformation goes from in-active to active...
                    // PDI-5229 sync added
                    synchronized (transListeners) {
                        for (TransListener listener : transListeners) {
                            listener.transActive(Trans.this);
                        }
                    }
                }
            }

            public void stepFinished(Trans trans, StepMeta stepMeta, StepInterface step) {
                synchronized (Trans.this) {
                    nrOfFinishedSteps++;

                    if (nrOfFinishedSteps >= steps.size()) {
                        // Set the finished flag
                        //
                        setFinished(true);

                        // Grab the performance statistics one last time (if enabled)
                        //
                        addStepPerformanceSnapShot();

                        try {
                            fireTransFinishedListeners();
                        } catch (Exception e) {
                            step.setErrors(step.getErrors() + 1L);
                            log.logError(getName() + " : " + BaseMessages.getString(PKG,
                                    "Trans.Log.UnexpectedErrorAtTransformationEnd"), e);
                        }
                    }

                    // If a step fails with an error, we want to kill/stop the others
                    // too...
                    //
                    if (step.getErrors() > 0) {

                        log.logMinimal(BaseMessages.getString(PKG, "Trans.Log.TransformationDetectedErrors"));
                        log.logMinimal(
                                BaseMessages.getString(PKG, "Trans.Log.TransformationIsKillingTheOtherSteps"));

                        killAllNoWait();
                    }
                }
            }
        };
        // Make sure this is called first!
        //
        if (sid.step instanceof BaseStep) {
            ((BaseStep) sid.step).getStepListeners().add(0, stepListener);
        } else {
            sid.step.addStepListener(stepListener);
        }
    }

    if (transMeta.isCapturingStepPerformanceSnapShots()) {
        stepPerformanceSnapshotSeqNr = new AtomicInteger(0);
        stepPerformanceSnapShots = new ConcurrentHashMap<String, List<StepPerformanceSnapShot>>();

        // Calculate the maximum number of snapshots to be kept in memory
        //
        String limitString = environmentSubstitute(transMeta.getStepPerformanceCapturingSizeLimit());
        if (Const.isEmpty(limitString)) {
            limitString = EnvUtil.getSystemProperty(Const.KETTLE_STEP_PERFORMANCE_SNAPSHOT_LIMIT);
        }
        stepPerformanceSnapshotSizeLimit = Const.toInt(limitString, 0);

        // Set a timer to collect the performance data from the running threads...
        //
        stepPerformanceSnapShotTimer = new Timer("stepPerformanceSnapShot Timer: " + transMeta.getName());
        TimerTask timerTask = new TimerTask() {
            public void run() {
                if (!isFinished()) {
                    addStepPerformanceSnapShot();
                }
            }
        };
        stepPerformanceSnapShotTimer.schedule(timerTask, 100, transMeta.getStepPerformanceCapturingDelay());
    }

    // Now start a thread to monitor the running transformation...
    //
    setFinished(false);
    paused.set(false);
    stopped.set(false);

    transFinishedBlockingQueue = new ArrayBlockingQueue<Object>(10);

    TransListener transListener = new TransAdapter() {
        public void transFinished(Trans trans) {

            try {
                ExtensionPointHandler.callExtensionPoint(log, KettleExtensionPoint.TransformationFinish.id,
                        trans);
            } catch (KettleException e) {
                throw new RuntimeException("Error calling extension point at end of transformation", e);
            }

            // First of all, stop the performance snapshot timer if there is is
            // one...
            //
            if (transMeta.isCapturingStepPerformanceSnapShots() && stepPerformanceSnapShotTimer != null) {
                stepPerformanceSnapShotTimer.cancel();
            }

            setFinished(true);
            running = false; // no longer running

            log.snap(Metrics.METRIC_TRANSFORMATION_EXECUTION_STOP);

            // If the user ran with metrics gathering enabled and a metrics logging table is configured, add another
            // listener...
            //
            MetricsLogTable metricsLogTable = transMeta.getMetricsLogTable();
            if (metricsLogTable.isDefined()) {
                try {
                    writeMetricsInformation();
                } catch (Exception e) {
                    log.logError("Error writing metrics information", e);
                    errors.incrementAndGet();
                }
            }

            // Close the unique connections when running database transactionally.
            // This will commit or roll back the transaction based on the result of this transformation.
            //
            if (transMeta.isUsingUniqueConnections()) {
                trans.closeUniqueDatabaseConnections(getResult());
            }
        }
    };
    // This should always be done first so that the other listeners achieve a clean state to start from (setFinished and
    // so on)
    //
    transListeners.add(0, transListener);

    running = true;

    switch (transMeta.getTransformationType()) {
    case Normal:

        // Now start all the threads...
        //
        for (int i = 0; i < steps.size(); i++) {
            final StepMetaDataCombi combi = steps.get(i);
            RunThread runThread = new RunThread(combi);
            Thread thread = new Thread(runThread);
            thread.setName(getName() + " - " + combi.stepname);
            ExtensionPointHandler.callExtensionPoint(log, KettleExtensionPoint.StepBeforeStart.id, combi);
            // Call an extension point at the end of the step
            //
            combi.step.addStepListener(new StepAdapter() {

                @Override
                public void stepFinished(Trans trans, StepMeta stepMeta, StepInterface step) {
                    try {
                        ExtensionPointHandler.callExtensionPoint(log, KettleExtensionPoint.StepFinished.id,
                                combi);
                    } catch (KettleException e) {
                        throw new RuntimeException(
                                "Unexpected error in calling extension point upon step finish", e);
                    }
                }

            });

            thread.start();
        }
        break;

    case SerialSingleThreaded:
        new Thread(new Runnable() {
            public void run() {
                try {
                    // Always disable thread priority management, it will always slow us
                    // down...
                    //
                    for (StepMetaDataCombi combi : steps) {
                        combi.step.setUsingThreadPriorityManagment(false);
                    }

                    //
                    // This is a single threaded version...
                    //

                    // Sort the steps from start to finish...
                    //
                    Collections.sort(steps, new Comparator<StepMetaDataCombi>() {
                        public int compare(StepMetaDataCombi c1, StepMetaDataCombi c2) {

                            boolean c1BeforeC2 = transMeta.findPrevious(c2.stepMeta, c1.stepMeta);
                            if (c1BeforeC2) {
                                return -1;
                            } else {
                                return 1;
                            }
                        }
                    });

                    boolean[] stepDone = new boolean[steps.size()];
                    int nrDone = 0;
                    while (nrDone < steps.size() && !isStopped()) {
                        for (int i = 0; i < steps.size() && !isStopped(); i++) {
                            StepMetaDataCombi combi = steps.get(i);
                            if (!stepDone[i]) {
                                // if (combi.step.canProcessOneRow() ||
                                // !combi.step.isRunning()) {
                                boolean cont = combi.step.processRow(combi.meta, combi.data);
                                if (!cont) {
                                    stepDone[i] = true;
                                    nrDone++;
                                }
                                // }
                            }
                        }
                    }
                } catch (Exception e) {
                    errors.addAndGet(1);
                    log.logError("Error executing single threaded", e);
                } finally {
                    for (int i = 0; i < steps.size(); i++) {
                        StepMetaDataCombi combi = steps.get(i);
                        combi.step.dispose(combi.meta, combi.data);
                        combi.step.markStop();
                    }
                }
            }
        }).start();
        break;

    case SingleThreaded:
        // Don't do anything, this needs to be handled by the transformation
        // executor!
        //
        break;
    default:
        break;

    }

    ExtensionPointHandler.callExtensionPoint(log, KettleExtensionPoint.TransformationStarted.id, this);

    if (log.isDetailed()) {
        log.logDetailed(BaseMessages.getString(PKG, "Trans.Log.TransformationHasAllocated",
                String.valueOf(steps.size()), String.valueOf(rowsets.size())));
    }
}