<commit_before>/*
 *   Copyright (c) 2020 Project CHIP Authors
 *   All rights reserved.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 */

#include "Commands.h"

#include "Command.h"
#include "Logging.h"

#include <algorithm>
#include <string>

#include <support/CHIPMem.h>

void Commands::Register(const char * clusterName, commands_list commandsList)
{
    for (auto & command : commandsList)
    {
        mClusters[clusterName].push_back(std::move(command));
    }
}

int Commands::Run(NodeId localId, NodeId remoteId, int argc, char ** argv)
{
    ConfigureChipLogging();

    CHIP_ERROR err = chip::Platform::MemoryInit();
    if (err != CHIP_NO_ERROR)
    {
        ChipLogError(Controller, "Init Memory failure: %s", chip::ErrorStr(err));
    }
    else
    {

        ChipDeviceController dc;

        err = dc.Init(localId);
        VerifyOrExit(err == CHIP_NO_ERROR, ChipLogError(Controller, "Init failure: %s", chip::ErrorStr(err)));

        err = dc.ServiceEvents();
        VerifyOrExit(err == CHIP_NO_ERROR, ChipLogError(Controller, "Init Run Loop failure: %s", chip::ErrorStr(err)));

        err = RunCommand(dc, remoteId, argc, argv);
        SuccessOrExit(err);

    exit:
        dc.ServiceEventSignal();
        dc.Shutdown();
    }
    return (err == CHIP_NO_ERROR) ? EXIT_SUCCESS : EXIT_FAILURE;
}

CHIP_ERROR Commands::RunCommand(ChipDeviceController & dc, NodeId remoteId, int argc, char ** argv)
{
    CHIP_ERROR err = CHIP_NO_ERROR;
    std::map<std::string, CommandsVector>::iterator cluster;
    Command * command = nullptr;

    if (argc <= 1)
    {
        ChipLogError(chipTool, "Missing cluster name");
        ShowClusters(argv[0]);
        ExitNow(err = CHIP_ERROR_INVALID_ARGUMENT);
    }

    cluster = GetCluster(argv[1]);
    if (cluster == mClusters.end())
    {
        ChipLogError(chipTool, "Unknown cluster: %s", argv[1]);
        ShowClusters(argv[0]);
        ExitNow(err = CHIP_ERROR_INVALID_ARGUMENT);
    }

    if (argc <= 2)
    {
        ChipLogError(chipTool, "Missing command name");
        ShowCluster(argv[0], argv[1], cluster->second);
        ExitNow(err = CHIP_ERROR_INVALID_ARGUMENT);
    }

    if (strcmp(argv[2], "read") != 0 && strcmp(argv[2], "write") != 0)
    {
        command = GetCommand(cluster->second, argv[2]);
        if (command == nullptr)
        {
            ChipLogError(chipTool, "Unknown command: %s", argv[2]);
            ShowCluster(argv[0], argv[1], cluster->second);
            ExitNow(err = CHIP_ERROR_INVALID_ARGUMENT);
        }
    }
    else
    {
        if (argc <= 3)
        {
            ChipLogError(chipTool, "Missing attribute name");
            ShowClusterAttributes(argv[0], argv[1], argv[2], cluster->second);
            ExitNow(err = CHIP_ERROR_INVALID_ARGUMENT);
        }

        command = GetReadWriteCommand(cluster->second, argv[2], argv[3]);
        if (command == nullptr)
        {
            ChipLogError(chipTool, "Unknown attribute: %s", argv[3]);
            ShowClusterAttributes(argv[0], argv[1], argv[2], cluster->second);
            ExitNow(err = CHIP_ERROR_INVALID_ARGUMENT);
        }
    }

    if (!command->InitArguments(argc - 3, &argv[3]))
    {
        ShowCommand(argv[0], argv[1], command);
        ExitNow(err = CHIP_ERROR_INVALID_ARGUMENT);
    }

    err = command->Run(&dc, remoteId);
    if (err != CHIP_NO_ERROR)
    {
        ChipLogError(chipTool, "Run command failure: %s", chip::ErrorStr(err));
        ExitNow();
    }

exit:
    return err;
}

std::map<std::string, Commands::CommandsVector>::iterator Commands::GetCluster(std::string clusterName)
{
    for (auto & cluster : mClusters)
    {
        std::string key(cluster.first);
        std::transform(key.begin(), key.end(), key.begin(), ::tolower);
        if (key.compare(clusterName) == 0)
        {
            return mClusters.find(cluster.first);
        }
    }

    return mClusters.end();
}

Command * Commands::GetCommand(CommandsVector & commands, std::string commandName)
{
    for (auto & command : commands)
    {
        if (commandName.compare(command->GetName()) == 0)
        {
            return command.get();
        }
    }

    return nullptr;
}

Command * Commands::GetReadWriteCommand(CommandsVector & commands, std::string commandName, std::string attributeName)
{
    for (auto & command : commands)
    {
        if (commandName.compare(command->GetName()) == 0 && attributeName.compare(command->GetAttribute()) == 0)
        {
            return command.get();
        }
    }

    return nullptr;
}

void Commands::ShowClusters(std::string executable)
{
    fprintf(stderr, "Usage:\n");
    fprintf(stderr, "  %s cluster_name command_name [param1 param2 ...]\n", executable.c_str());
    fprintf(stderr, "\n");
    fprintf(stderr, "  +-------------------------------------------------------------------------------------+\n");
    fprintf(stderr, "  | Clusters:                                                                           |\n");
    fprintf(stderr, "  +-------------------------------------------------------------------------------------+\n");
    for (auto & cluster : mClusters)
    {
        fprintf(stderr, "  | * %-82s|\n", cluster.first.c_str());
    }
    fprintf(stderr, "  +-------------------------------------------------------------------------------------+\n");
}

void Commands::ShowCluster(std::string executable, std::string clusterName, CommandsVector & commands)
{
    fprintf(stderr, "Usage:\n");
    fprintf(stderr, "  %s %s command_name [param1 param2 ...]\n", executable.c_str(), clusterName.c_str());
    fprintf(stderr, "\n");
    fprintf(stderr, "  +-------------------------------------------------------------------------------------+\n");
    fprintf(stderr, "  | Commands:                                                                           |\n");
    fprintf(stderr, "  +-------------------------------------------------------------------------------------+\n");
    bool readCommand  = false;
    bool writeCommand = false;
    for (auto & command : commands)
    {
        if (strcmp(command->GetName(), "read") == 0)
        {
            if (readCommand == false)
            {
                fprintf(stderr, "  | * %-82s|\n", command->GetName());
                readCommand = true;
            }
        }
        else if (strcmp(command->GetName(), "write") == 0)
        {
            if (writeCommand == false)
            {
                fprintf(stderr, "  | * %-82s|\n", command->GetName());
                writeCommand = true;
            }
        }
        else
        {
            fprintf(stderr, "  | * %-82s|\n", command->GetName());
        }
    }
    fprintf(stderr, "  +-------------------------------------------------------------------------------------+\n");
}

void Commands::ShowClusterAttributes(std::string executable, std::string clusterName, std::string commandName,
                                     CommandsVector & commands)
{
    fprintf(stderr, "Usage:\n");
    fprintf(stderr, "  %s %s %s attribute-name [param1 param2 ...]\n", executable.c_str(), clusterName.c_str(),
            commandName.c_str());
    fprintf(stderr, "\n");
    fprintf(stderr, "  +-------------------------------------------------------------------------------------+\n");
    fprintf(stderr, "  | Attributes:                                                                         |\n");
    fprintf(stderr, "  +-------------------------------------------------------------------------------------+\n");
    for (auto & command : commands)
    {
        if (commandName.compare(command->GetName()) == 0)
        {
            fprintf(stderr, "  | * %-82s|\n", command->GetAttribute());
        }
    }
    fprintf(stderr, "  +-------------------------------------------------------------------------------------+\n");
}

void Commands::ShowCommand(std::string executable, std::string clusterName, Command * command)
{
    fprintf(stderr, "Usage:\n");

    std::string arguments = "";
    arguments += command->GetName();

    size_t argumentsCount = command->GetArgumentsCount();
    for (size_t i = 0; i < argumentsCount; i++)
    {
        arguments += " ";
        arguments += command->GetArgumentName(i);
    }
    fprintf(stderr, "  %s %s %s\n", executable.c_str(), clusterName.c_str(), arguments.c_str());
}
<commit_msg>Print cluster name in lowercase for chip-tool so it match what is expected on the command line (#3531)<commit_after>/*
 *   Copyright (c) 2020 Project CHIP Authors
 *   All rights reserved.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 */

#include "Commands.h"

#include "Command.h"
#include "Logging.h"

#include <algorithm>
#include <string>

#include <support/CHIPMem.h>

void Commands::Register(const char * clusterName, commands_list commandsList)
{
    for (auto & command : commandsList)
    {
        mClusters[clusterName].push_back(std::move(command));
    }
}

int Commands::Run(NodeId localId, NodeId remoteId, int argc, char ** argv)
{
    ConfigureChipLogging();

    CHIP_ERROR err = chip::Platform::MemoryInit();
    if (err != CHIP_NO_ERROR)
    {
        ChipLogError(Controller, "Init Memory failure: %s", chip::ErrorStr(err));
    }
    else
    {

        ChipDeviceController dc;

        err = dc.Init(localId);
        VerifyOrExit(err == CHIP_NO_ERROR, ChipLogError(Controller, "Init failure: %s", chip::ErrorStr(err)));

        err = dc.ServiceEvents();
        VerifyOrExit(err == CHIP_NO_ERROR, ChipLogError(Controller, "Init Run Loop failure: %s", chip::ErrorStr(err)));

        err = RunCommand(dc, remoteId, argc, argv);
        SuccessOrExit(err);

    exit:
        dc.ServiceEventSignal();
        dc.Shutdown();
    }
    return (err == CHIP_NO_ERROR) ? EXIT_SUCCESS : EXIT_FAILURE;
}

CHIP_ERROR Commands::RunCommand(ChipDeviceController & dc, NodeId remoteId, int argc, char ** argv)
{
    CHIP_ERROR err = CHIP_NO_ERROR;
    std::map<std::string, CommandsVector>::iterator cluster;
    Command * command = nullptr;

    if (argc <= 1)
    {
        ChipLogError(chipTool, "Missing cluster name");
        ShowClusters(argv[0]);
        ExitNow(err = CHIP_ERROR_INVALID_ARGUMENT);
    }

    cluster = GetCluster(argv[1]);
    if (cluster == mClusters.end())
    {
        ChipLogError(chipTool, "Unknown cluster: %s", argv[1]);
        ShowClusters(argv[0]);
        ExitNow(err = CHIP_ERROR_INVALID_ARGUMENT);
    }

    if (argc <= 2)
    {
        ChipLogError(chipTool, "Missing command name");
        ShowCluster(argv[0], argv[1], cluster->second);
        ExitNow(err = CHIP_ERROR_INVALID_ARGUMENT);
    }

    if (strcmp(argv[2], "read") != 0 && strcmp(argv[2], "write") != 0)
    {
        command = GetCommand(cluster->second, argv[2]);
        if (command == nullptr)
        {
            ChipLogError(chipTool, "Unknown command: %s", argv[2]);
            ShowCluster(argv[0], argv[1], cluster->second);
            ExitNow(err = CHIP_ERROR_INVALID_ARGUMENT);
        }
    }
    else
    {
        if (argc <= 3)
        {
            ChipLogError(chipTool, "Missing attribute name");
            ShowClusterAttributes(argv[0], argv[1], argv[2], cluster->second);
            ExitNow(err = CHIP_ERROR_INVALID_ARGUMENT);
        }

        command = GetReadWriteCommand(cluster->second, argv[2], argv[3]);
        if (command == nullptr)
        {
            ChipLogError(chipTool, "Unknown attribute: %s", argv[3]);
            ShowClusterAttributes(argv[0], argv[1], argv[2], cluster->second);
            ExitNow(err = CHIP_ERROR_INVALID_ARGUMENT);
        }
    }

    if (!command->InitArguments(argc - 3, &argv[3]))
    {
        ShowCommand(argv[0], argv[1], command);
        ExitNow(err = CHIP_ERROR_INVALID_ARGUMENT);
    }

    err = command->Run(&dc, remoteId);
    if (err != CHIP_NO_ERROR)
    {
        ChipLogError(chipTool, "Run command failure: %s", chip::ErrorStr(err));
        ExitNow();
    }

exit:
    return err;
}

std::map<std::string, Commands::CommandsVector>::iterator Commands::GetCluster(std::string clusterName)
{
    for (auto & cluster : mClusters)
    {
        std::string key(cluster.first);
        std::transform(key.begin(), key.end(), key.begin(), ::tolower);
        if (key.compare(clusterName) == 0)
        {
            return mClusters.find(cluster.first);
        }
    }

    return mClusters.end();
}

Command * Commands::GetCommand(CommandsVector & commands, std::string commandName)
{
    for (auto & command : commands)
    {
        if (commandName.compare(command->GetName()) == 0)
        {
            return command.get();
        }
    }

    return nullptr;
}

Command * Commands::GetReadWriteCommand(CommandsVector & commands, std::string commandName, std::string attributeName)
{
    for (auto & command : commands)
    {
        if (commandName.compare(command->GetName()) == 0 && attributeName.compare(command->GetAttribute()) == 0)
        {
            return command.get();
        }
    }

    return nullptr;
}

void Commands::ShowClusters(std::string executable)
{
    fprintf(stderr, "Usage:\n");
    fprintf(stderr, "  %s cluster_name command_name [param1 param2 ...]\n", executable.c_str());
    fprintf(stderr, "\n");
    fprintf(stderr, "  +-------------------------------------------------------------------------------------+\n");
    fprintf(stderr, "  | Clusters:                                                                           |\n");
    fprintf(stderr, "  +-------------------------------------------------------------------------------------+\n");
    for (auto & cluster : mClusters)
    {
        std::string clusterName(cluster.first);
        std::transform(clusterName.begin(), clusterName.end(), clusterName.begin(),
                       [](unsigned char c) { return std::tolower(c); });
        fprintf(stderr, "  | * %-82s|\n", clusterName.c_str());
    }
    fprintf(stderr, "  +-------------------------------------------------------------------------------------+\n");
}

void Commands::ShowCluster(std::string executable, std::string clusterName, CommandsVector & commands)
{
    fprintf(stderr, "Usage:\n");
    fprintf(stderr, "  %s %s command_name [param1 param2 ...]\n", executable.c_str(), clusterName.c_str());
    fprintf(stderr, "\n");
    fprintf(stderr, "  +-------------------------------------------------------------------------------------+\n");
    fprintf(stderr, "  | Commands:                                                                           |\n");
    fprintf(stderr, "  +-------------------------------------------------------------------------------------+\n");
    bool readCommand  = false;
    bool writeCommand = false;
    for (auto & command : commands)
    {
        if (strcmp(command->GetName(), "read") == 0)
        {
            if (readCommand == false)
            {
                fprintf(stderr, "  | * %-82s|\n", command->GetName());
                readCommand = true;
            }
        }
        else if (strcmp(command->GetName(), "write") == 0)
        {
            if (writeCommand == false)
            {
                fprintf(stderr, "  | * %-82s|\n", command->GetName());
                writeCommand = true;
            }
        }
        else
        {
            fprintf(stderr, "  | * %-82s|\n", command->GetName());
        }
    }
    fprintf(stderr, "  +-------------------------------------------------------------------------------------+\n");
}

void Commands::ShowClusterAttributes(std::string executable, std::string clusterName, std::string commandName,
                                     CommandsVector & commands)
{
    fprintf(stderr, "Usage:\n");
    fprintf(stderr, "  %s %s %s attribute-name [param1 param2 ...]\n", executable.c_str(), clusterName.c_str(),
            commandName.c_str());
    fprintf(stderr, "\n");
    fprintf(stderr, "  +-------------------------------------------------------------------------------------+\n");
    fprintf(stderr, "  | Attributes:                                                                         |\n");
    fprintf(stderr, "  +-------------------------------------------------------------------------------------+\n");
    for (auto & command : commands)
    {
        if (commandName.compare(command->GetName()) == 0)
        {
            fprintf(stderr, "  | * %-82s|\n", command->GetAttribute());
        }
    }
    fprintf(stderr, "  +-------------------------------------------------------------------------------------+\n");
}

void Commands::ShowCommand(std::string executable, std::string clusterName, Command * command)
{
    fprintf(stderr, "Usage:\n");

    std::string arguments = "";
    arguments += command->GetName();

    size_t argumentsCount = command->GetArgumentsCount();
    for (size_t i = 0; i < argumentsCount; i++)
    {
        arguments += " ";
        arguments += command->GetArgumentName(i);
    }
    fprintf(stderr, "  %s %s %s\n", executable.c_str(), clusterName.c_str(), arguments.c_str());
}
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <sstream>

#include <ignite/common/common.h>
#include <ignite/common/concurrent.h>
#include <ignite/common/exports.h>
#include <ignite/common/java.h>

#include "ignite/impl/ignite_environment.h"
#include "ignite/impl/ignite_impl.h"
#include "ignite/impl/utils.h"
#include "ignite/ignition.h"

using namespace ignite::common::concurrent;
using namespace ignite::common::java;
using namespace ignite::impl;
using namespace ignite::impl::utils;

namespace ignite
{
    /** Default configuration. */
    const char* DFLT_CFG = "config/default-config.xml";

    /** Whether JVM library is loaded to the process. */
    bool JVM_LIB_LOADED;

    /** Critical section for factory methods. */
    CriticalSection factoryLock;

    /** Flag indicating that at least one Ignite instance has started. */
    bool started = false;

    /**
     * Convert integer value to string.
     */
    std::string JvmMemoryString(const std::string& prefix, int32_t val)
    {
        std::ostringstream ss;
        ss << val;

        std::string valStr = ss.str();

        std::string res = std::string(prefix);
        res.append(valStr);
        res.append("m");

        return res;
    }

    /**
     * Create JVM options.
     *
     * @param cfg Configuration.
     * @param home Optional GG home.
     * @param cp Classpath.
     * @param opts Options.
     * @param optsLen Options length.
     * @return Options.
     */
    char** CreateJvmOptions(const IgniteConfiguration& cfg, const std::string* home, const std::string& cp, int* optsLen)
    {
        *optsLen = 3 + (home ? 1 : 0) + cfg.jvmOptsLen;
        char** opts = new char*[*optsLen];

        int idx = 0;

        // 1. Set classpath.
        std::string cpFull = std::string("-Djava.class.path=") + cp;

        *(opts + idx++) = CopyChars(cpFull.c_str());

        // 2. Set home.
        if (home) {
            std::string homeFull = std::string("-DIGNITE_HOME=") + *home;

            *(opts + idx++) = CopyChars(homeFull.c_str());
        }

        // 3. Set Xms, Xmx.
        std::string xmsStr = JvmMemoryString(std::string("-Xms"), cfg.jvmInitMem);
        std::string xmxStr = JvmMemoryString(std::string("-Xmx"), cfg.jvmMaxMem);

        *(opts + idx++) = CopyChars(xmsStr.c_str());
        *(opts + idx++) = CopyChars(xmxStr.c_str());

        // 4. Set the rest options.
        for (int i = 0; i < cfg.jvmOptsLen; i++) {
            char* optCopy = CopyChars(cfg.jvmOpts[i].opt);

            opts[idx++] = optCopy;
        }

        return opts;
    }

    Ignite Ignition::Start(const IgniteConfiguration& cfg)
    {
        return Start(cfg, static_cast<const char*>(NULL));
    }

    Ignite Ignition::Start(const IgniteConfiguration& cfg, IgniteError* err)
    {
        return Start(cfg, NULL, err);
    }

    Ignite Ignition::Start(const IgniteConfiguration& cfg, const char* name)
    {
        IgniteError err;

        Ignite res = Start(cfg, name, &err);

        IgniteError::ThrowIfNeeded(err);

        return res;
    }

    Ignite Ignition::Start(const IgniteConfiguration& cfg, const char* name, IgniteError* err)
    {
        bool failed = false;

        SharedPointer<IgniteEnvironment> env;
        SharedPointer<IgniteEnvironment>* envTarget = NULL;

        jobject javaRef = NULL;

        factoryLock.Enter();

        // 1. Load JVM library if needed.
        if (!JVM_LIB_LOADED)
        {
            bool jvmLibFound;
            std::string jvmLib;

            if (cfg.jvmLibPath)
            {
                std::string jvmLibPath = std::string(cfg.jvmLibPath);

                jvmLib = FindJvmLibrary(&jvmLibPath, &jvmLibFound);
            }
            else
                jvmLib = FindJvmLibrary(NULL, &jvmLibFound);

            if (!jvmLibFound)
            {
                *err = IgniteError(IgniteError::IGNITE_ERR_JVM_LIB_NOT_FOUND,
                    "JVM library is not found (did you set JAVA_HOME environment variable?)");

                failed = true;
            }
            else
                std::cout << "JVM LIB LOC: " << jvmLib << std::endl;

            if (!failed) {
                if (!LoadJvmLibrary(jvmLib))
                {
                    *err = IgniteError(IgniteError::IGNITE_ERR_JVM_LIB_LOAD_FAILED, "Failed to load JVM library.");

                    failed = true;
                }
            }

            JVM_LIB_LOADED = true;
        }

        if (!failed)
        {
            // 2. Resolve IGNITE_HOME.
            bool homeFound;
            std::string home;

            if (cfg.igniteHome)
            {
                std::string homePath = std::string(cfg.igniteHome);

                home = ResolveIgniteHome(&homePath, &homeFound);
            }
            else
                home = ResolveIgniteHome(NULL, &homeFound);

            std::cout << "IGNITE_HOME: " << home << std::endl;

            // 3. Create classpath.
            std::string cp;

            if (cfg.jvmClassPath)
            {
                std::string usrCp = cfg.jvmClassPath;

                cp = CreateIgniteClasspath(&usrCp, homeFound ? &home : NULL);
            }
            else
                cp = CreateIgniteClasspath(NULL, homeFound ? &home : NULL);

            if (!cp.empty())
            {
                std::cout << "CLASSPATH: " << cp << std::endl;

                // 4. Start JVM if needed.
                JniErrorInfo jniErr;

                env = SharedPointer<IgniteEnvironment>(new IgniteEnvironment());

                int optsLen;
                char** opts = CreateJvmOptions(cfg, homeFound ? &home : NULL, cp, &optsLen);

                envTarget = new SharedPointer<IgniteEnvironment>(env);

                SharedPointer<JniContext> ctx(
                    JniContext::Create(opts, optsLen, env.Get()->GetJniHandlers(envTarget), &jniErr));

                for (int i = 0; i < optsLen; i++)
                    ReleaseChars(*(opts + i));

                delete[] opts;

                if (!ctx.Get())
                {
                    IgniteError::SetError(jniErr.code, jniErr.errCls, jniErr.errMsg, err);

                    failed = true;
                }

                // 5. Start Ignite.
                if (!failed)
                {
                    char* springCfgPath0 = CopyChars(cfg.springCfgPath);

                    if (!springCfgPath0)
                        springCfgPath0 = CopyChars(DFLT_CFG);

                    char* name0 = CopyChars(name);

                    interop::InteropUnpooledMemory mem(16);
                    interop::InteropOutputStream stream(&mem);
                    stream.WriteBool(false);
                    stream.Synchronize();

                    javaRef = ctx.Get()->IgnitionStart(springCfgPath0, name0, 2, mem.PointerLong(), &jniErr);

                    ReleaseChars(springCfgPath0);
                    ReleaseChars(name0);

                    if (!javaRef) {
                        IgniteError::SetError(jniErr.code, jniErr.errCls, jniErr.errMsg, err);

                        failed = true;
                    }
                    else {
                        // 6. Ignite is started at this point.
                        env.Get()->Initialize(ctx);

                        started = true;
                    }
                }
            }
            else {
                *err = IgniteError(IgniteError::IGNITE_ERR_JVM_NO_CLASSPATH,
                    "Java classpath is empty (did you set IGNITE_HOME environment variable?)");

                failed = true;
            }
        }

        factoryLock.Leave();

        if (failed)
        {
            if (envTarget)
                delete envTarget;

            return Ignite();
        }
        else
        {
            IgniteImpl* impl = new IgniteImpl(env, javaRef);

            return Ignite(impl);
        }
    }

    Ignite Ignition::Get()
    {
        return Get(static_cast<const char*>(NULL));
    }

    Ignite Ignition::Get(IgniteError* err)
    {
        return Get(NULL, err);
    }

    Ignite Ignition::Get(const char* name)
    {
        IgniteError err;

        Ignite res = Get(name, &err);

        IgniteError::ThrowIfNeeded(err);

        return res;
    }

    Ignite Ignition::Get(const char* name, IgniteError* err)
    {
        Ignite res;

        factoryLock.Enter();

        if (started)
        {
            char* name0 = CopyChars(name);

            // 1. Create context for this operation.
            JniErrorInfo jniErr;

            SharedPointer<JniContext> ctx(JniContext::Create(NULL, 0, JniHandlers(), &jniErr));

            IgniteError::SetError(jniErr.code, jniErr.errCls, jniErr.errMsg, err);

            if (err->GetCode() == IgniteError::IGNITE_SUCCESS)
            {
                // 2. Get environment pointer.
                long long ptr = ctx.Get()->IgnitionEnvironmentPointer(name0, &jniErr);

                IgniteError::SetError(jniErr.code, jniErr.errCls, jniErr.errMsg, err);

                if (err->GetCode() == IgniteError::IGNITE_SUCCESS)
                {
                    if (ptr != 0)
                    {
                        // 3. Obtain real environment for this instance.
                        JniHandlers* hnds = reinterpret_cast<JniHandlers*>(ptr);

                        SharedPointer<IgniteEnvironment>* env =
                            static_cast<SharedPointer<IgniteEnvironment>*>(hnds->target);

                        // 4. Get fresh node reference.
                        jobject ref = ctx.Get()->IgnitionInstance(name0, &jniErr);

                        if (err->GetCode() == IgniteError::IGNITE_SUCCESS) {
                            if (ref)
                            {
                                IgniteImpl* impl = new IgniteImpl(*env, ref);

                                res = Ignite(impl);
                            }
                            else
                                // Error: concurrent node stop.
                                *err = IgniteError(IgniteError::IGNITE_ERR_GENERIC,
                                    "Failed to get Ignite instance because it was stopped concurrently.");

                        }
                    }
                    else
                        // Error: no node with the given name.
                        *err = IgniteError(IgniteError::IGNITE_ERR_GENERIC,
                            "Failed to get Ignite instance because it is either not started yet or already stopped.");
                }
            }

            ReleaseChars(name0);
        }
        else
            // Error: no node with the given name.
            *err = IgniteError(IgniteError::IGNITE_ERR_GENERIC,
                "Failed to get Ignite instance because it is either not started yet or already stopped.");

        factoryLock.Leave();

        return res;
    }

    bool Ignition::Stop(const bool cancel)
    {
        return Stop(NULL, cancel);
    }

    bool Ignition::Stop(const bool cancel, IgniteError* err)
    {
        return Stop(NULL, cancel, err);
    }

    bool Ignition::Stop(const char* name, const bool cancel)
    {
        IgniteError err;

        bool res = Stop(name, cancel, &err);

        IgniteError::ThrowIfNeeded(err);

        return res;
    }

    bool Ignition::Stop(const char* name, const bool cancel, IgniteError* err)
    {
        bool res = false;

        factoryLock.Enter();

        if (started)
        {
            JniErrorInfo jniErr;

            SharedPointer<JniContext> ctx(JniContext::Create(NULL, 0, JniHandlers(), &jniErr));

            IgniteError::SetError(jniErr.code, jniErr.errCls, jniErr.errMsg, err);

            if (err->GetCode() == IgniteError::IGNITE_SUCCESS)
            {
                char* name0 = CopyChars(name);

                bool res0 = ctx.Get()->IgnitionStop(name0, cancel, &jniErr);

                ReleaseChars(name0);

                IgniteError::SetError(jniErr.code, jniErr.errCls, jniErr.errMsg, err);

                if (err->GetCode() == IgniteError::IGNITE_SUCCESS)
                    res = res0;
            }
        }

        factoryLock.Leave();

        return res;
    }

    void Ignition::StopAll(const bool cancel)
    {
        IgniteError err;

        StopAll(cancel, &err);

        IgniteError::ThrowIfNeeded(err);
    }

    void Ignition::StopAll(const bool cancel, IgniteError* err)
    {
        factoryLock.Enter();

        if (started)
        {
            JniErrorInfo jniErr;

            SharedPointer<JniContext> ctx(JniContext::Create(NULL, 0, JniHandlers(), &jniErr));

            IgniteError::SetError(jniErr.code, jniErr.errCls, jniErr.errMsg, err);

            if (err->GetCode() == IgniteError::IGNITE_SUCCESS)
            {
                ctx.Get()->IgnitionStopAll(cancel, &jniErr);

                IgniteError::SetError(jniErr.code, jniErr.errCls, jniErr.errMsg, err);
            }
        }

        factoryLock.Leave();
    }
}
<commit_msg>Debug (2).<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <sstream>

#include <ignite/common/common.h>
#include <ignite/common/concurrent.h>
#include <ignite/common/exports.h>
#include <ignite/common/java.h>

#include "ignite/impl/ignite_environment.h"
#include "ignite/impl/ignite_impl.h"
#include "ignite/impl/utils.h"
#include "ignite/ignition.h"

using namespace ignite::common::java;
using namespace ignite::impl;
using namespace ignite::impl::utils;

namespace ignite
{
    /** Default configuration. */
    const char* DFLT_CFG = "config/default-config.xml";

    /** Whether JVM library is loaded to the process. */
    bool JVM_LIB_LOADED;

    /** Critical section for factory methods. */
    CriticalSection factoryLock;

    /** Flag indicating that at least one Ignite instance has started. */
    bool started = false;

    /**
     * Convert integer value to string.
     */
    std::string JvmMemoryString(const std::string& prefix, int32_t val)
    {
        std::ostringstream ss;
        ss << val;

        std::string valStr = ss.str();

        std::string res = std::string(prefix);
        res.append(valStr);
        res.append("m");

        return res;
    }

    /**
     * Create JVM options.
     *
     * @param cfg Configuration.
     * @param home Optional GG home.
     * @param cp Classpath.
     * @param opts Options.
     * @param optsLen Options length.
     * @return Options.
     */
    char** CreateJvmOptions(const IgniteConfiguration& cfg, const std::string* home, const std::string& cp, int* optsLen)
    {
        *optsLen = 3 + (home ? 1 : 0) + cfg.jvmOptsLen;
        char** opts = new char*[*optsLen];

        int idx = 0;

        // 1. Set classpath.
        std::string cpFull = std::string("-Djava.class.path=") + cp;

        *(opts + idx++) = CopyChars(cpFull.c_str());

        // 2. Set home.
        if (home) {
            std::string homeFull = std::string("-DIGNITE_HOME=") + *home;

            *(opts + idx++) = CopyChars(homeFull.c_str());
        }

        // 3. Set Xms, Xmx.
        std::string xmsStr = JvmMemoryString(std::string("-Xms"), cfg.jvmInitMem);
        std::string xmxStr = JvmMemoryString(std::string("-Xmx"), cfg.jvmMaxMem);

        *(opts + idx++) = CopyChars(xmsStr.c_str());
        *(opts + idx++) = CopyChars(xmxStr.c_str());

        // 4. Set the rest options.
        for (int i = 0; i < cfg.jvmOptsLen; i++) {
            char* optCopy = CopyChars(cfg.jvmOpts[i].opt);

            opts[idx++] = optCopy;
        }

        return opts;
    }

    Ignite Ignition::Start(const IgniteConfiguration& cfg)
    {
        return Start(cfg, static_cast<const char*>(NULL));
    }

    Ignite Ignition::Start(const IgniteConfiguration& cfg, IgniteError* err)
    {
        return Start(cfg, NULL, err);
    }

    Ignite Ignition::Start(const IgniteConfiguration& cfg, const char* name)
    {
        IgniteError err;

        Ignite res = Start(cfg, name, &err);

        IgniteError::ThrowIfNeeded(err);

        return res;
    }

    Ignite Ignition::Start(const IgniteConfiguration& cfg, const char* name, IgniteError* err)
    {
        bool failed = false;

        SharedPointer<IgniteEnvironment> env;
        SharedPointer<IgniteEnvironment>* envTarget = NULL;

        jobject javaRef = NULL;

        factoryLock.Enter();

        // 1. Load JVM library if needed.
        if (!JVM_LIB_LOADED)
        {
            bool jvmLibFound;
            std::string jvmLib;

            if (cfg.jvmLibPath)
            {
                std::string jvmLibPath = std::string(cfg.jvmLibPath);

                jvmLib = FindJvmLibrary(&jvmLibPath, &jvmLibFound);
            }
            else
                jvmLib = FindJvmLibrary(NULL, &jvmLibFound);

            if (!jvmLibFound)
            {
                *err = IgniteError(IgniteError::IGNITE_ERR_JVM_LIB_NOT_FOUND,
                    "JVM library is not found (did you set JAVA_HOME environment variable?)");

                failed = true;
            }
            else
                std::cout << "JVM LIB LOC: " << jvmLib << std::endl;

            if (!failed) {
                if (!LoadJvmLibrary(jvmLib))
                {
                    *err = IgniteError(IgniteError::IGNITE_ERR_JVM_LIB_LOAD_FAILED, "Failed to load JVM library.");

                    failed = true;
                }
            }

            JVM_LIB_LOADED = true;
        }

        if (!failed)
        {
            // 2. Resolve IGNITE_HOME.
            bool homeFound;
            std::string home;

            if (cfg.igniteHome)
            {
                std::string homePath = std::string(cfg.igniteHome);

                home = ResolveIgniteHome(&homePath, &homeFound);
            }
            else
                home = ResolveIgniteHome(NULL, &homeFound);

            std::cout << "IGNITE_HOME: " << home << std::endl;

            // 3. Create classpath.
            std::string cp;

            if (cfg.jvmClassPath)
            {
                std::string usrCp = cfg.jvmClassPath;

                cp = CreateIgniteClasspath(&usrCp, homeFound ? &home : NULL);
            }
            else
                cp = CreateIgniteClasspath(NULL, homeFound ? &home : NULL);

            if (!cp.empty())
            {
                std::cout << "CLASSPATH: " << cp << std::endl;

                // 4. Start JVM if needed.
                JniErrorInfo jniErr;

                env = SharedPointer<IgniteEnvironment>(new IgniteEnvironment());

                int optsLen;
                char** opts = CreateJvmOptions(cfg, homeFound ? &home : NULL, cp, &optsLen);

                envTarget = new SharedPointer<IgniteEnvironment>(env);

                SharedPointer<JniContext> ctx(
                    JniContext::Create(opts, optsLen, env.Get()->GetJniHandlers(envTarget), &jniErr));

                for (int i = 0; i < optsLen; i++)
                    ReleaseChars(*(opts + i));

                delete[] opts;

                if (!ctx.Get())
                {
                    IgniteError::SetError(jniErr.code, jniErr.errCls, jniErr.errMsg, err);

                    failed = true;
                }

                // 5. Start Ignite.
                if (!failed)
                {
                    char* springCfgPath0 = CopyChars(cfg.springCfgPath);

                    if (!springCfgPath0)
                        springCfgPath0 = CopyChars(DFLT_CFG);

                    char* name0 = CopyChars(name);

                    interop::InteropUnpooledMemory mem(16);
                    interop::InteropOutputStream stream(&mem);
                    stream.WriteBool(false);
                    stream.Synchronize();

                    javaRef = ctx.Get()->IgnitionStart(springCfgPath0, name0, 2, mem.PointerLong(), &jniErr);

                    ReleaseChars(springCfgPath0);
                    ReleaseChars(name0);

                    if (!javaRef) {
                        IgniteError::SetError(jniErr.code, jniErr.errCls, jniErr.errMsg, err);

                        failed = true;
                    }
                    else {
                        // 6. Ignite is started at this point.
                        env.Get()->Initialize(ctx);

                        started = true;
                    }
                }
            }
            else {
                *err = IgniteError(IgniteError::IGNITE_ERR_JVM_NO_CLASSPATH,
                    "Java classpath is empty (did you set IGNITE_HOME environment variable?)");

                failed = true;
            }
        }

        factoryLock.Leave();

        if (failed)
        {
            if (envTarget)
                delete envTarget;

            return Ignite();
        }
        else
        {
            IgniteImpl* impl = new IgniteImpl(env, javaRef);

            return Ignite(impl);
        }
    }

    Ignite Ignition::Get()
    {
        return Get(static_cast<const char*>(NULL));
    }

    Ignite Ignition::Get(IgniteError* err)
    {
        return Get(NULL, err);
    }

    Ignite Ignition::Get(const char* name)
    {
        IgniteError err;

        Ignite res = Get(name, &err);

        IgniteError::ThrowIfNeeded(err);

        return res;
    }

    Ignite Ignition::Get(const char* name, IgniteError* err)
    {
        Ignite res;

        factoryLock.Enter();

        if (started)
        {
            char* name0 = CopyChars(name);

            // 1. Create context for this operation.
            JniErrorInfo jniErr;

            SharedPointer<JniContext> ctx(JniContext::Create(NULL, 0, JniHandlers(), &jniErr));

            IgniteError::SetError(jniErr.code, jniErr.errCls, jniErr.errMsg, err);

            if (err->GetCode() == IgniteError::IGNITE_SUCCESS)
            {
                // 2. Get environment pointer.
                long long ptr = ctx.Get()->IgnitionEnvironmentPointer(name0, &jniErr);

                IgniteError::SetError(jniErr.code, jniErr.errCls, jniErr.errMsg, err);

                if (err->GetCode() == IgniteError::IGNITE_SUCCESS)
                {
                    if (ptr != 0)
                    {
                        // 3. Obtain real environment for this instance.
                        JniHandlers* hnds = reinterpret_cast<JniHandlers*>(ptr);

                        SharedPointer<IgniteEnvironment>* env =
                            static_cast<SharedPointer<IgniteEnvironment>*>(hnds->target);

                        // 4. Get fresh node reference.
                        jobject ref = ctx.Get()->IgnitionInstance(name0, &jniErr);

                        if (err->GetCode() == IgniteError::IGNITE_SUCCESS) {
                            if (ref)
                            {
                                IgniteImpl* impl = new IgniteImpl(*env, ref);

                                res = Ignite(impl);
                            }
                            else
                                // Error: concurrent node stop.
                                *err = IgniteError(IgniteError::IGNITE_ERR_GENERIC,
                                    "Failed to get Ignite instance because it was stopped concurrently.");

                        }
                    }
                    else
                        // Error: no node with the given name.
                        *err = IgniteError(IgniteError::IGNITE_ERR_GENERIC,
                            "Failed to get Ignite instance because it is either not started yet or already stopped.");
                }
            }

            ReleaseChars(name0);
        }
        else
            // Error: no node with the given name.
            *err = IgniteError(IgniteError::IGNITE_ERR_GENERIC,
                "Failed to get Ignite instance because it is either not started yet or already stopped.");

        factoryLock.Leave();

        return res;
    }

    bool Ignition::Stop(const bool cancel)
    {
        return Stop(NULL, cancel);
    }

    bool Ignition::Stop(const bool cancel, IgniteError* err)
    {
        return Stop(NULL, cancel, err);
    }

    bool Ignition::Stop(const char* name, const bool cancel)
    {
        IgniteError err;

        bool res = Stop(name, cancel, &err);

        IgniteError::ThrowIfNeeded(err);

        return res;
    }

    bool Ignition::Stop(const char* name, const bool cancel, IgniteError* err)
    {
        bool res = false;

        factoryLock.Enter();

        if (started)
        {
            JniErrorInfo jniErr;

            SharedPointer<JniContext> ctx(JniContext::Create(NULL, 0, JniHandlers(), &jniErr));

            IgniteError::SetError(jniErr.code, jniErr.errCls, jniErr.errMsg, err);

            if (err->GetCode() == IgniteError::IGNITE_SUCCESS)
            {
                char* name0 = CopyChars(name);

                bool res0 = ctx.Get()->IgnitionStop(name0, cancel, &jniErr);

                ReleaseChars(name0);

                IgniteError::SetError(jniErr.code, jniErr.errCls, jniErr.errMsg, err);

                if (err->GetCode() == IgniteError::IGNITE_SUCCESS)
                    res = res0;
            }
        }

        factoryLock.Leave();

        return res;
    }

    void Ignition::StopAll(const bool cancel)
    {
        IgniteError err;

        StopAll(cancel, &err);

        IgniteError::ThrowIfNeeded(err);
    }

    void Ignition::StopAll(const bool cancel, IgniteError* err)
    {
        factoryLock.Enter();

        if (started)
        {
            JniErrorInfo jniErr;

            SharedPointer<JniContext> ctx(JniContext::Create(NULL, 0, JniHandlers(), &jniErr));

            IgniteError::SetError(jniErr.code, jniErr.errCls, jniErr.errMsg, err);

            if (err->GetCode() == IgniteError::IGNITE_SUCCESS)
            {
                ctx.Get()->IgnitionStopAll(cancel, &jniErr);

                IgniteError::SetError(jniErr.code, jniErr.errCls, jniErr.errMsg, err);
            }
        }

        factoryLock.Leave();
    }
}
<|endoftext|>


<commit_before>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4      *
*                (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS                    *
*                                                                             *
* This library is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU Lesser General Public License as published by    *
* the Free Software Foundation; either version 2.1 of the License, or (at     *
* your option) any later version.                                             *
*                                                                             *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details.                                                           *
*                                                                             *
* You should have received a copy of the GNU Lesser General Public License    *
* along with this library; if not, write to the Free Software Foundation,     *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.          *
*******************************************************************************
*                              SOFA :: Framework                              *
*                                                                             *
* Authors: M. Adam, J. Allard, B. Andre, P-J. Bensoussan, S. Cotin, C. Duriez,*
* H. Delingette, F. Falipou, F. Faure, S. Fonteneau, L. Heigeas, C. Mendoza,  *
* M. Nesme, P. Neumann, J-P. de la Plata Alcade, F. Poyer and F. Roy          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
#include <sofa/helper/io/MeshTrian.h>
#include <sofa/helper/system/FileRepository.h>
#include <stdlib.h>
#include <iostream>
#include <string>

#include <cstdio>

namespace sofa
{

namespace helper
{

namespace io
{

using namespace sofa::defaulttype;

SOFA_DECL_CLASS(MeshTrian)

Creator<Mesh::FactoryMesh,MeshTrian> MeshTrianClass("trian");

void MeshTrian::init (std::string filename)
{
    if (!sofa::helper::system::DataRepository.findFile(filename))
    {
        std::cerr << "File " << filename << " not found " << std::endl;
        return;
    }
    FILE *f = fopen(filename.c_str(), "r");
    if (f)
    {
        readTrian (f);
        fclose(f);
    }
    else
        std::cerr << "File " << filename << " not found " << std::endl;
}

void MeshTrian::readTrian (FILE* file)
{
    int nbp=0;

    if (fscanf(file, "%d\n", &nbp) == EOF)
        std::cerr << "Error: MeshTrian: fscanf function has encountered an error." << std::endl;

    vertices.resize(nbp);
    Vec3d fromFile;
    for (int p=0; p<nbp; p++)
    {
        if (fscanf(file, "%lf %lf %lf\n", &fromFile[0], &fromFile[1], &fromFile[2]) == EOF)
            std::cerr << "Error: MeshTrian: fscanf function has encountered an error." << std::endl;
        vertices[p][0] = (SReal)fromFile[0];
        vertices[p][1] = (SReal)fromFile[1];
        vertices[p][2] = (SReal)fromFile[2];
    }

    int nbf=0;
    if (fscanf(file, "%d\n", &nbf) == EOF )
        std::cerr << "Error: MeshTrian: fscanf function has encountered an error." << std::endl;

    facets.resize(nbf);
    for (int f=0; f<nbf; f++)
    {
        facets[f].resize(3);
        facets[f][0].resize(3);
        facets[f][1].resize(3);
        facets[f][2].resize(3);
        int dummy = 0;
        if ( fscanf(file, "%d %d %d %d %d %d\n", &facets[f][0][0], &facets[f][0][1], &facets[f][0][2], &dummy, &dummy, &dummy) )
            std::cerr << "Error: MeshTrian: fscanf function has encountered an error." << std::endl;
    }

    // announce the model statistics
    std::cout << " Vertices: " << vertices.size() << std::endl;
    std::cout << " Normals: " << normals.size() << std::endl;
    std::cout << " Texcoords: " << texCoords.size() << std::endl;
    std::cout << " Triangles: " << facets.size() << std::endl;
    if (vertices.size()>0)
    {
        // compute bbox
        Vector3 minBB = vertices[0];
        Vector3 maxBB = vertices[0];
        for (unsigned int i=1; i<vertices.size(); i++)
        {
            Vector3 p = vertices[i];
            for (int c=0; c<3; c++)
            {
                if (minBB[c] > p[c])
                    minBB[c] = p[c];
                if (maxBB[c] < p[c])
                    maxBB[c] = p[c];
            }
        }

        std::cout << "BBox: <"<<minBB[0]<<','<<minBB[1]<<','<<minBB[2]<<">-<"<<maxBB[0]<<','<<maxBB[1]<<','<<maxBB[2]<<">\n";
    }

}

} // namespace io

} // namespace helper

} // namespace sofa

<commit_msg>r5441/sofa-dev : FIX: error log were displayed even if loading was successful.<commit_after>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4      *
*                (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS                    *
*                                                                             *
* This library is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU Lesser General Public License as published by    *
* the Free Software Foundation; either version 2.1 of the License, or (at     *
* your option) any later version.                                             *
*                                                                             *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details.                                                           *
*                                                                             *
* You should have received a copy of the GNU Lesser General Public License    *
* along with this library; if not, write to the Free Software Foundation,     *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.          *
*******************************************************************************
*                              SOFA :: Framework                              *
*                                                                             *
* Authors: M. Adam, J. Allard, B. Andre, P-J. Bensoussan, S. Cotin, C. Duriez,*
* H. Delingette, F. Falipou, F. Faure, S. Fonteneau, L. Heigeas, C. Mendoza,  *
* M. Nesme, P. Neumann, J-P. de la Plata Alcade, F. Poyer and F. Roy          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
#include <sofa/helper/io/MeshTrian.h>
#include <sofa/helper/system/FileRepository.h>
#include <stdlib.h>
#include <iostream>
#include <string>

#include <cstdio>

namespace sofa
{

namespace helper
{

namespace io
{

using namespace sofa::defaulttype;

SOFA_DECL_CLASS(MeshTrian)

Creator<Mesh::FactoryMesh,MeshTrian> MeshTrianClass("trian");

void MeshTrian::init (std::string filename)
{
    if (!sofa::helper::system::DataRepository.findFile(filename))
    {
        std::cerr << "File " << filename << " not found " << std::endl;
        return;
    }
    FILE *f = fopen(filename.c_str(), "r");
    if (f)
    {
        readTrian (f);
        fclose(f);
    }
    else
        std::cerr << "File " << filename << " not found " << std::endl;
}

void MeshTrian::readTrian (FILE* file)
{
    int nbp=0;

    if (fscanf(file, "%d\n", &nbp) == EOF)
        std::cerr << "Error: MeshTrian: fscanf function has encountered an error." << std::endl;

    vertices.resize(nbp);
    Vec3d fromFile;
    for (int p=0; p<nbp; p++)
    {
        if (fscanf(file, "%lf %lf %lf\n", &fromFile[0], &fromFile[1], &fromFile[2]) == EOF)
            std::cerr << "Error: MeshTrian: fscanf function has encountered an error." << std::endl;
        vertices[p][0] = (SReal)fromFile[0];
        vertices[p][1] = (SReal)fromFile[1];
        vertices[p][2] = (SReal)fromFile[2];
    }

    int nbf=0;
    if (fscanf(file, "%d\n", &nbf) == EOF )
        std::cerr << "Error: MeshTrian: fscanf function has encountered an error." << std::endl;

    facets.resize(nbf);
    for (int f=0; f<nbf; f++)
    {
        facets[f].resize(3);
        facets[f][0].resize(3);
        facets[f][1].resize(3);
        facets[f][2].resize(3);
        int dummy = 0;
        if ( fscanf(file, "%d %d %d %d %d %d\n", &facets[f][0][0], &facets[f][0][1], &facets[f][0][2], &dummy, &dummy, &dummy) == EOF )
            std::cerr << "Error: MeshTrian: fscanf function has encountered an error." << std::endl;
    }

    // announce the model statistics
    std::cout << " Vertices: " << vertices.size() << std::endl;
    std::cout << " Normals: " << normals.size() << std::endl;
    std::cout << " Texcoords: " << texCoords.size() << std::endl;
    std::cout << " Triangles: " << facets.size() << std::endl;
    if (vertices.size()>0)
    {
        // compute bbox
        Vector3 minBB = vertices[0];
        Vector3 maxBB = vertices[0];
        for (unsigned int i=1; i<vertices.size(); i++)
        {
            Vector3 p = vertices[i];
            for (int c=0; c<3; c++)
            {
                if (minBB[c] > p[c])
                    minBB[c] = p[c];
                if (maxBB[c] < p[c])
                    maxBB[c] = p[c];
            }
        }

        std::cout << "BBox: <"<<minBB[0]<<','<<minBB[1]<<','<<minBB[2]<<">-<"<<maxBB[0]<<','<<maxBB[1]<<','<<maxBB[2]<<">\n";
    }

}

} // namespace io

} // namespace helper

} // namespace sofa

<|endoftext|>


<commit_before>#include "BombDefender.h"

#include <string.h>
#include <GLES3/gl3.h>
#include <jni.h>
#include <iostream>
#include <glm/gtc/matrix_transform.hpp>
#include <Context.h>
#include <AndroidPlatform.h>
#include <ContextAndroid.h>
#include <VBO.h>
#include <OpenGLTexture.h>
#include <TextureRef.h>

using namespace std;
using namespace gpufw;

std::shared_ptr<canvas::Context> context;
int positionX = 120;
int positionY = 120;
std::shared_ptr<canvas::Surface> yoSurface;
canvas::TextureRef texture;

bool BombDefender::Init() {

  test_program = std::shared_ptr<gpufw::shader_program>(new gpufw::shader_program);

  test_program->loadShaders(getPlatform().getGLSLVersion(), "simple_sprite_shader.glsl");
  test_program->bindAttribLocation(0, "a_texCoord");
  test_program->bindAttribLocation(1, "a_position");
  test_program->link();
}

void BombDefender::onDraw() {

  if (!texture.getTextureId()) {
//    __android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Texture is null");
    auto contextF = getPlatform().createContextFactory();
    context = contextF->createContext(256, 256, canvas::InternalFormat::RGBA8, true);

    context->globalAlpha = 1.0f;
    context->font.size = 50;
    context->textBaseline = "top";
    yoSurface = context->createSurface("picture.jpg");
    context->drawImage(*yoSurface, 0, 0, 256, 256);

    texture = canvas::OpenGLTexture::createTexture(context->getDefaultSurface());
  }

  Sprite sprite;
  drawSprite(sprite);
//  auto contextF = getPlatform().createContextFactory();
//  context = contextF->createContext(500, 500, canvas::InternalFormat::RGBA8, true);
//
//  context->globalAlpha = 1.0f;
//  context->font.size = 50;
//  context->textBaseline = "top";
//  yoSurface = context->createSurface("picture.jpg");
//
//  context->drawImage(*yoSurface, positionX, positionY, 200, 200);
//  positionX--;
//  positionY--;
//	__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Application ondraw");
//  dynamic_cast<AndroidPlatform&>(getPlatform()).showCanvas(dynamic_cast<canvas::ContextAndroid&>(*context));

}

void BombDefender::drawSprite(const Sprite & sprite){

  glm::mat4 projMat = glm::ortho(0.0f, 640.0f, 0.0f, 480.0f, -1000.0f, +1000.0f);
  glm::mat4 mat(1.0f);

  use(*test_program);
  test_program->setUniform("proj_mv_matrix", projMat * mat);
  test_program->setUniform("s_texture", 0);

  glDisable(GL_DEPTH_TEST);
  glDisable(GL_STENCIL_TEST);
  glDisable(GL_CULL_FACE);
  glEnable(GL_BLEND);
  glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
  glDepthMask(GL_FALSE);

  glActiveTexture(GL_TEXTURE0);
  glBindTexture(GL_TEXTURE_2D, texture.getTextureId());

  VBO vbo;
  vbo.quad2d(10.0f, 10.0f,
  	   500.0f, 10.0f,
  	   500.0f, 500.0f,
  	   10.0f, 500.0f);

  bind(vbo);

//	__android_log_print(ANDROID_LOG_INFO, "Sometrik", "BomdDefender texture id: %d", texture->getTextureId());
//	__android_log_print(ANDROID_LOG_INFO, "Sometrik", "BomdDefender IndexBufferId id: %d", vbo.getIndexBufferId());

  vbo.draw();

  glBindTexture(GL_TEXTURE_2D, 0);
}

void BombDefender::onShutdown() {
}

void
BombDefender::use(const gpufw::shader_program & program) {
  int id = program.getProgramObjectId();
//  	__android_log_print(ANDROID_LOG_INFO, "Sometrik", "BomdDefender use id: %d", id);
  if (!id) {
    assert(0);
  }
    glUseProgram(id);
}

void
BombDefender::bind(const VBO & vbo) {
  if (vbo.hasVertexArrayObjects()) {
    assert(vbo.getVertexArrayId());
    glBindVertexArray(vbo.getVertexArrayId());
  } else {
    assert(vbo.getVertexBufferId() && vbo.getIndexBufferId());
    glBindBuffer(GL_ARRAY_BUFFER, vbo.getVertexBufferId());
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo.getIndexBufferId());
    vbo.setPointers();
  }
}

std::shared_ptr<BombDefender> application;

void applicationMain(FWPlatformBase * platform) {
  application = std::make_shared<BombDefender>(platform);
  platform->setApplication(application.get());

}
<commit_msg>add OpenGL error checking<commit_after>#include "BombDefender.h"

#include <string.h>
#include <GLES3/gl3.h>
#include <jni.h>
#include <iostream>
#include <glm/gtc/matrix_transform.hpp>
#include <Context.h>
#include <AndroidPlatform.h>
#include <ContextAndroid.h>
#include <VBO.h>
#include <OpenGLTexture.h>
#include <TextureRef.h>

using namespace std;
using namespace gpufw;

std::shared_ptr<canvas::Context> context;
int positionX = 120;
int positionY = 120;
std::shared_ptr<canvas::Surface> yoSurface;
canvas::TextureRef texture;

static void checkGLError() {
  GLenum errLast = GL_NO_ERROR;
  for ( ;; ) {
    GLenum err = glGetError();
    if ( err == GL_NO_ERROR ) {
      return;
    }

    // normally the error is reset by the call to glGetError() but if
    // glGetError() itself returns an error, we risk looping forever here
    // so check that we get a different error than the last time
    if ( err == errLast ) {
      cerr << "OpenGL error state couldn't be reset.\n";
      return;
    }

    errLast = err;

    cerr << "got OpenGL error " << err << "\n";
  }
}

bool BombDefender::Init() {
  test_program = std::shared_ptr<gpufw::shader_program>(new gpufw::shader_program);

  test_program->loadShaders(getPlatform().getGLSLVersion(), "simple_sprite_shader.glsl");
  test_program->bindAttribLocation(0, "a_texCoord");
  test_program->bindAttribLocation(1, "a_position");
  test_program->link();
}

void BombDefender::onDraw() {

  if (!texture.getTextureId()) {
//    __android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Texture is null");
    auto contextF = getPlatform().createContextFactory();
    context = contextF->createContext(256, 256, canvas::InternalFormat::RGBA8, true);

    context->globalAlpha = 1.0f;
    context->font.size = 50;
    context->textBaseline = "top";
    yoSurface = context->createSurface("picture.jpg");
    context->drawImage(*yoSurface, 0, 0, 256, 256);

    texture = canvas::OpenGLTexture::createTexture(context->getDefaultSurface());
  }

  Sprite sprite;
  drawSprite(sprite);
//  auto contextF = getPlatform().createContextFactory();
//  context = contextF->createContext(500, 500, canvas::InternalFormat::RGBA8, true);
//
//  context->globalAlpha = 1.0f;
//  context->font.size = 50;
//  context->textBaseline = "top";
//  yoSurface = context->createSurface("picture.jpg");
//
//  context->drawImage(*yoSurface, positionX, positionY, 200, 200);
//  positionX--;
//  positionY--;
//	__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Application ondraw");
//  dynamic_cast<AndroidPlatform&>(getPlatform()).showCanvas(dynamic_cast<canvas::ContextAndroid&>(*context));

  checkGLError();
}

void BombDefender::drawSprite(const Sprite & sprite){

  glm::mat4 projMat = glm::ortho(0.0f, 640.0f, 0.0f, 480.0f, -1000.0f, +1000.0f);
  glm::mat4 mat(1.0f);

  use(*test_program);
  test_program->setUniform("proj_mv_matrix", projMat * mat);
  test_program->setUniform("s_texture", 0);

  glDisable(GL_DEPTH_TEST);
  glDisable(GL_STENCIL_TEST);
  glDisable(GL_CULL_FACE);
  glEnable(GL_BLEND);
  glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
  glDepthMask(GL_FALSE);

  glActiveTexture(GL_TEXTURE0);
  glBindTexture(GL_TEXTURE_2D, texture.getTextureId());

  VBO vbo;
  vbo.quad2d(10.0f, 10.0f,
  	   500.0f, 10.0f,
  	   500.0f, 500.0f,
  	   10.0f, 500.0f);

  bind(vbo);

//	__android_log_print(ANDROID_LOG_INFO, "Sometrik", "BomdDefender texture id: %d", texture->getTextureId());
//	__android_log_print(ANDROID_LOG_INFO, "Sometrik", "BomdDefender IndexBufferId id: %d", vbo.getIndexBufferId());

  vbo.draw();

  glBindTexture(GL_TEXTURE_2D, 0);
}

void BombDefender::onShutdown() {
}

void
BombDefender::use(const gpufw::shader_program & program) {
  int id = program.getProgramObjectId();
//  	__android_log_print(ANDROID_LOG_INFO, "Sometrik", "BomdDefender use id: %d", id);
  if (!id) {
    assert(0);
  }
    glUseProgram(id);
}

void
BombDefender::bind(const VBO & vbo) {
  if (vbo.hasVertexArrayObjects()) {
    assert(vbo.getVertexArrayId());
    glBindVertexArray(vbo.getVertexArrayId());
  } else {
    assert(vbo.getVertexBufferId() && vbo.getIndexBufferId());
    glBindBuffer(GL_ARRAY_BUFFER, vbo.getVertexBufferId());
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo.getIndexBufferId());
    vbo.setPointers();
  }
}

std::shared_ptr<BombDefender> application;

void applicationMain(FWPlatformBase * platform) {
  application = std::make_shared<BombDefender>(platform);
  platform->setApplication(application.get());

}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: dp_misc.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: obo $ $Date: 2004-08-12 12:08:13 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2002 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "dp_misc.h"
#include "dp_interact.h"
#include "rtl/uri.hxx"
#include "rtl/digest.h"
#include "rtl/random.h"
#include "rtl/bootstrap.hxx"
#include "osl/file.hxx"
#include "osl/pipe.hxx"
#include "osl/security.hxx"
#include "osl/thread.hxx"
#include "osl/mutex.hxx"
#include "com/sun/star/ucb/CommandAbortedException.hpp"
#include "com/sun/star/bridge/UnoUrlResolver.hpp"
#include "com/sun/star/bridge/XUnoUrlResolver.hpp"

using ::rtl::OUString;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;

namespace dp_misc {

static OUString s_platform, s_os = OUSTR("$_OS"), s_arch = OUSTR("$_ARCH");

//==============================================================================
OUString const & getPlatformString()
{
    if (s_platform.getLength() == 0) {
        ::osl::MutexGuard guard( ::osl::Mutex::getGlobalMutex() );
        ::rtl::Bootstrap::expandMacros( s_os );
        ::rtl::Bootstrap::expandMacros( s_arch );
        ::rtl::OUStringBuffer buf;
        buf.append( s_os );
        buf.append( static_cast<sal_Unicode>('_') );
        buf.append( s_arch );
        s_platform = buf.makeStringAndClear();
    }
    return s_platform;
}
//==============================================================================
bool platform_fits( OUString const & platform_string )
{
    OUString const & thisPlatform = getPlatformString();
    sal_Int32 index = 0;
    for (;;) {
        OUString token( platform_string.getToken( 0, ',', index ).trim() );
        // check if this platform:
        if (token.equalsIgnoreAsciiCase( thisPlatform ) ||
            (token.indexOf( '_' ) < 0 && /* check OS part only */
             token.equalsIgnoreAsciiCase( s_os ))) {
            return true;
        }
        if (index < 0)
            break;
    }
    return false;
}

//==============================================================================
OUString make_url( OUString const & base_url, OUString const & url )
{
    // xxx todo: wait for SB's api
    ::rtl::OUStringBuffer buf;
    buf.append( base_url );
    if (base_url.getLength() > 0 &&
        base_url[ base_url.getLength() - 1 ] != '/') {
        buf.append( static_cast< sal_Unicode >('/') );
    }
    if (url.getLength() > 0 && url[ 0 ] == '/')
        buf.append( url.copy( 1 ) );
    else
        buf.append( url );
    return buf.makeStringAndClear();
}

//==============================================================================
OUString expand_url( OUString const & url )
{
    if (url.matchIgnoreAsciiCaseAsciiL(
            RTL_CONSTASCII_STRINGPARAM("vnd.sun.star.expand:") )) {
        static ::rtl::Bootstrap * s_punorc = 0;
        if (s_punorc == 0) {
            OUString unorc = OUSTR("$ORIGIN/" SAL_CONFIGFILE("uno"));
            ::rtl::Bootstrap::expandMacros( unorc );
            static ::rtl::Bootstrap s_unorc( unorc );
            OSL_ASSERT( s_unorc.getHandle() != 0 );
            s_punorc = &s_unorc;
        }

        // cut protocol:
        OUString macro( url.copy( sizeof ("vnd.sun.star.expand:") - 1 ) );
        // decode uric class chars:
        macro = ::rtl::Uri::decode(
            macro, rtl_UriDecodeWithCharset, RTL_TEXTENCODING_UTF8 );
        // expand macro string:
        s_punorc->expandMacrosFrom( macro );
        return macro;
    } else {
        return url;
    }
}

//==============================================================================
bool office_is_running()
{
    static OUString s_pipeId;
    if (s_pipeId.getLength() == 0) {
        OUString userPath = OUSTR("${$SYSBINDIR/" SAL_CONFIGFILE("bootstrap")
                                  ":UserInstallation}");
        ::rtl::Bootstrap::expandMacros( userPath );
        OSL_ASSERT( userPath.getLength() > 0 );

        // normalize path:
        ::osl::FileStatus status( FileStatusMask_FileURL );
        ::osl::DirectoryItem dirItem;
        if (::osl::DirectoryItem::get( userPath, dirItem )
            != ::osl::DirectoryItem::E_None ||
            dirItem.getFileStatus( status )
            != ::osl::DirectoryItem::E_None ||
            !status.isValid( FileStatusMask_FileURL ) ||
            ::osl::FileBase::getAbsoluteFileURL(
                OUString(), status.getFileURL(), userPath )
            != ::osl::FileBase::E_None) {
            return false;
        }

        rtlDigest digest = rtl_digest_create( rtl_Digest_AlgorithmMD5 );
        if (digest <= 0)
            throw RuntimeException(
                OUSTR("cannot get digest rtl_Digest_AlgorithmMD5!"), 0 );

        sal_uInt8 const * data =
            reinterpret_cast< sal_uInt8 const * >(userPath.getStr());
        sal_Size size = (userPath.getLength() * sizeof (sal_Unicode));
        sal_uInt32 md5_key_len = rtl_digest_queryLength( digest );
        sal_uInt8 * md5_buf = new sal_uInt8 [ md5_key_len ];

        rtl_digest_init( digest, data, static_cast<sal_uInt32>(size) );
        rtl_digest_update( digest, data, static_cast<sal_uInt32>(size) );
        rtl_digest_get( digest, md5_buf, md5_key_len );
        rtl_digest_destroy( digest );

        // create hex-value string from the MD5 value to keep
        // the string size minimal
        ::rtl::OUStringBuffer buf;
        buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("SingleOfficeIPC_") );
        for ( sal_uInt32 i = 0; i < md5_key_len; ++i )
            buf.append( static_cast<sal_Int32>(md5_buf[ i ]), 0x10 );

        delete [] md5_buf;
        s_pipeId = buf.makeStringAndClear();
    }

    ::osl::Security sec;
    ::osl::Pipe pipe( s_pipeId, osl_Pipe_OPEN, sec );
    return pipe.is();
}

//==============================================================================
oslProcess raiseProcess(
    OUString const & appURL, Sequence<OUString> const & args )
{
    ::osl::Security sec;
    sal_Int32 pos = args.getLength();
    OUString const * pargs = args.getConstArray();
    rtl_uString ** parArgs = new rtl_uString * [ pos ];
    for ( ; pos--; )
        parArgs[ pos ] = pargs[ pos ].pData;

    oslProcess hProcess = 0;
    oslProcessError rc = osl_executeProcess(
        appURL.pData, parArgs, args.getLength(),
        osl_Process_DETACHED,
        sec.getHandle(),
        0, // => current working dir
        0, 0, // => no env vars
        &hProcess );
    delete [] parArgs;

    switch (rc) {
    case osl_Process_E_None:
        break;
    case osl_Process_E_NotFound:
        throw RuntimeException( OUSTR("image not found!"), 0 );
    case osl_Process_E_TimedOut:
        throw RuntimeException( OUSTR("timout occured!"), 0 );
    case osl_Process_E_NoPermission:
        throw RuntimeException( OUSTR("permission denied!"), 0 );
    case osl_Process_E_Unknown:
        throw RuntimeException( OUSTR("unknown error!"), 0 );
    case osl_Process_E_InvalidError:
    default:
        throw RuntimeException( OUSTR("unmapped error!"), 0 );
    }

    return hProcess;
}

//==============================================================================
OUString generateRandomPipeId()
{
    // compute some good pipe id:
    static rtlRandomPool s_hPool = rtl_random_createPool();
    if (s_hPool == 0)
        throw RuntimeException( OUSTR("cannot create random pool!?"), 0 );
    sal_uInt8 bytes[ 32 ];
    if (rtl_random_getBytes(
            s_hPool, bytes, ARLEN(bytes) ) != rtl_Random_E_None)
        throw RuntimeException( OUSTR("random pool error!?"), 0 );

    ::rtl::OUStringBuffer buf;
    for ( sal_uInt32 i = 0; i < ARLEN(bytes); ++i )
        buf.append( static_cast<sal_Int32>(bytes[ i ]), 0x10 );

    return buf.makeStringAndClear();
}

//==============================================================================
Reference<XInterface> resolveUnoURL(
    OUString const & connectString,
    Reference<XComponentContext> const & xLocalContext,
    AbortChannel * abortChannel )
{
    Reference<bridge::XUnoUrlResolver> xUnoUrlResolver(
        bridge::UnoUrlResolver::create( xLocalContext ) );

    for (;;) {
        if (abortChannel != 0 && abortChannel->isAborted())
            throw ucb::CommandAbortedException(
                OUSTR("abort!"), Reference<XInterface>() );

        try {
            return xUnoUrlResolver->resolve( connectString );
        }
        catch (connection::NoConnectException &) {
            TimeValue tv = { 0 /* secs */, 500000000 /* nanosecs */ };
            ::osl::Thread::wait( tv );
        }
    }
}

}
<commit_msg>INTEGRATION: CWS jl13 (1.6.12); FILE MERGED 2004/10/15 12:48:57 dbo 1.6.12.3: #i35536##i34555##i34149# - rc files without vnd.sun.star.expand urls - export file picker filter - reinstall cleans xlc files - minor improvements Issue number: Submitted by: Reviewed by: 2004/09/30 16:53:54 dbo 1.6.12.2: #i34555# correct double checked locking, misc cleanup 2004/09/14 15:31:43 dbo 1.6.12.1: #i34149##i33982# modified makeURL(), misc fixes<commit_after>/*************************************************************************
 *
 *  $RCSfile: dp_misc.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: hr $ $Date: 2004-11-09 14:09:07 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2002 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "dp_misc.h"
#include "dp_interact.h"
#include "rtl/uri.hxx"
#include "rtl/digest.h"
#include "rtl/random.h"
#include "rtl/bootstrap.hxx"
#include "osl/file.hxx"
#include "osl/pipe.hxx"
#include "osl/security.hxx"
#include "osl/thread.hxx"
#include "osl/mutex.hxx"
#include "com/sun/star/ucb/CommandAbortedException.hpp"
#include "com/sun/star/bridge/UnoUrlResolver.hpp"
#include "com/sun/star/bridge/XUnoUrlResolver.hpp"
#include "boost/scoped_array.hpp"
#include "boost/shared_ptr.hpp"

using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using ::rtl::OUString;

namespace dp_misc {
namespace {

struct StrOperatingSystem
    : public ::rtl::StaticData<OUString, StrOperatingSystem> {
    OUString operator () () {
        OUString os( RTL_CONSTASCII_USTRINGPARAM("$_OS") );
        ::rtl::Bootstrap::expandMacros( os );
        return os;
    }
};

struct StrPlatform : public ::rtl::StaticData<OUString, StrPlatform> {
    OUString operator () () {
        ::rtl::OUStringBuffer buf;
        buf.append( StrOperatingSystem::get() );
        buf.append( static_cast<sal_Unicode>('_') );
        OUString arch( RTL_CONSTASCII_USTRINGPARAM("$_ARCH") );
        ::rtl::Bootstrap::expandMacros( arch );
        buf.append( arch );
        return buf.makeStringAndClear();
    }
};

struct UnoRc : public ::rtl::StaticData<
    ::boost::shared_ptr< ::rtl::Bootstrap >, UnoRc > {
    ::boost::shared_ptr< ::rtl::Bootstrap > operator () () {
        OUString unorc( RTL_CONSTASCII_USTRINGPARAM(
                            "$ORIGIN/" SAL_CONFIGFILE("uno")) );
        ::rtl::Bootstrap::expandMacros( unorc );
        ::boost::shared_ptr< ::rtl::Bootstrap > ret(
            new ::rtl::Bootstrap( unorc ) );
        OSL_ASSERT( ret->getHandle() != 0 );
        return ret;
    }
};

struct OfficePipeId : public ::rtl::StaticData<OUString, OfficePipeId> {
    OUString operator () ();
};

OUString OfficePipeId::operator () ()
{
    OUString userPath = OUSTR("${$SYSBINDIR/" SAL_CONFIGFILE("bootstrap")
                              ":UserInstallation}");
    ::rtl::Bootstrap::expandMacros( userPath );
    OSL_ASSERT( userPath.getLength() > 0 );

    // normalize path:
    ::osl::FileStatus status( FileStatusMask_FileURL );
    ::osl::DirectoryItem dirItem;
    if (::osl::DirectoryItem::get( userPath, dirItem )
        != ::osl::DirectoryItem::E_None ||
        dirItem.getFileStatus( status )
        != ::osl::DirectoryItem::E_None ||
        !status.isValid( FileStatusMask_FileURL ) ||
        ::osl::FileBase::getAbsoluteFileURL(
            OUString(), status.getFileURL(), userPath )
        != ::osl::FileBase::E_None)
    {
        return OUString();
    }

    rtlDigest digest = rtl_digest_create( rtl_Digest_AlgorithmMD5 );
    if (digest <= 0) {
        throw RuntimeException(
            OUSTR("cannot get digest rtl_Digest_AlgorithmMD5!"), 0 );
    }

    sal_uInt8 const * data =
        reinterpret_cast<sal_uInt8 const *>(userPath.getStr());
    sal_Size size = (userPath.getLength() * sizeof (sal_Unicode));
    sal_uInt32 md5_key_len = rtl_digest_queryLength( digest );
    ::boost::scoped_array<sal_uInt8> md5_buf( new sal_uInt8 [ md5_key_len ] );

    rtl_digest_init( digest, data, static_cast<sal_uInt32>(size) );
    rtl_digest_update( digest, data, static_cast<sal_uInt32>(size) );
    rtl_digest_get( digest, md5_buf.get(), md5_key_len );
    rtl_digest_destroy( digest );

    // create hex-value string from the MD5 value to keep
    // the string size minimal
    ::rtl::OUStringBuffer buf;
    buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("SingleOfficeIPC_") );
    for ( sal_uInt32 i = 0; i < md5_key_len; ++i ) {
        buf.append( static_cast<sal_Int32>(md5_buf[ i ]), 0x10 );
    }
    return buf.makeStringAndClear();
}

} // anon namespace

//==============================================================================
OUString const & getPlatformString()
{
    return StrPlatform::get();
}

//==============================================================================
bool platform_fits( OUString const & platform_string )
{
    sal_Int32 index = 0;
    for (;;)
    {
        const OUString token(
            platform_string.getToken( 0, ',', index ).trim() );
        // check if this platform:
        if (token.equalsIgnoreAsciiCase( StrPlatform::get() ) ||
            (token.indexOf( '_' ) < 0 && /* check OS part only */
             token.equalsIgnoreAsciiCase( StrOperatingSystem::get() )))
        {
            return true;
        }
        if (index < 0)
            break;
    }
    return false;
}

namespace {
inline OUString encodeForRcFile( OUString const & str )
{
    // escape $\{} (=> rtl bootstrap files)
    ::rtl::OUStringBuffer buf;
    sal_Int32 pos = 0;
    const sal_Int32 len = str.getLength();
    for ( ; pos < len; ++pos ) {
        sal_Unicode c = str[ pos ];
        switch (c) {
        case '$':
        case '\\':
        case '{':
        case '}':
            buf.append( static_cast<sal_Unicode>('\\') );
            break;
        }
        buf.append( c );
    }
    return buf.makeStringAndClear();
}
}

//==============================================================================
OUString makeURL( OUString const & baseURL, OUString const & relPath_ )
{
    ::rtl::OUStringBuffer buf;
    if (baseURL.getLength() > 1 && baseURL[ baseURL.getLength() - 1 ] == '/')
        buf.append( baseURL.copy( 0, baseURL.getLength() - 1 ) );
    else
        buf.append( baseURL );
    OUString relPath(relPath_);
    if (relPath.getLength() > 0 && relPath[ 0 ] == '/')
        relPath = relPath.copy( 1 );
    if (relPath.getLength() > 0)
    {
        buf.append( static_cast<sal_Unicode>('/') );
        if (baseURL.matchAsciiL(
                RTL_CONSTASCII_STRINGPARAM("vnd.sun.star.expand:") )) {
            // encode for macro expansion: relPath is supposed to have no
            // macros, so encode $, {} \ (bootstrap mimic)
            relPath = encodeForRcFile(relPath);

            // encode once more for vnd.sun.star.expand schema:
            // vnd.sun.star.expand:$UNO_...
            // will expand to file-url
            relPath = ::rtl::Uri::encode( relPath, rtl_UriCharClassUric,
                                          rtl_UriEncodeIgnoreEscapes,
                                          RTL_TEXTENCODING_UTF8 );
        }
        buf.append( relPath );
    }
    return buf.makeStringAndClear();
}

//==============================================================================
OUString expandUnoRcTerm( OUString const & term_ )
{
    OUString term(term_);
    UnoRc::get()->expandMacrosFrom( term );
    return term;
}

//==============================================================================
OUString expandUnoRcUrl( OUString const & url )
{
    if (url.matchAsciiL( RTL_CONSTASCII_STRINGPARAM("vnd.sun.star.expand:") )) {
        // cut protocol:
        OUString rcurl( url.copy( sizeof ("vnd.sun.star.expand:") - 1 ) );
        // decode uric class chars:
        rcurl = ::rtl::Uri::decode(
            rcurl, rtl_UriDecodeWithCharset, RTL_TEXTENCODING_UTF8 );
        // expand macro string:
        UnoRc::get()->expandMacrosFrom( rcurl );
        return rcurl;
    }
    else {
        return url;
    }
}

//==============================================================================
bool office_is_running()
{
    OUString const & pipeId = OfficePipeId::get();
    if (pipeId.getLength() == 0)
        return false;
    ::osl::Security sec;
    ::osl::Pipe pipe( pipeId, osl_Pipe_OPEN, sec );
    return pipe.is();
}

//==============================================================================
oslProcess raiseProcess(
    OUString const & appURL, Sequence<OUString> const & args )
{
    ::osl::Security sec;
    oslProcess hProcess = 0;
    oslProcessError rc = osl_executeProcess(
        appURL.pData,
        reinterpret_cast<rtl_uString **>(
            const_cast<OUString *>(args.getConstArray()) ),
        args.getLength(),
        osl_Process_DETACHED,
        sec.getHandle(),
        0, // => current working dir
        0, 0, // => no env vars
        &hProcess );

    switch (rc) {
    case osl_Process_E_None:
        break;
    case osl_Process_E_NotFound:
        throw RuntimeException( OUSTR("image not found!"), 0 );
    case osl_Process_E_TimedOut:
        throw RuntimeException( OUSTR("timout occured!"), 0 );
    case osl_Process_E_NoPermission:
        throw RuntimeException( OUSTR("permission denied!"), 0 );
    case osl_Process_E_Unknown:
        throw RuntimeException( OUSTR("unknown error!"), 0 );
    case osl_Process_E_InvalidError:
    default:
        throw RuntimeException( OUSTR("unmapped error!"), 0 );
    }

    return hProcess;
}

//==============================================================================
OUString generateRandomPipeId()
{
    // compute some good pipe id:
    static rtlRandomPool s_hPool = rtl_random_createPool();
    if (s_hPool == 0)
        throw RuntimeException( OUSTR("cannot create random pool!?"), 0 );
    sal_uInt8 bytes[ 32 ];
    if (rtl_random_getBytes(
            s_hPool, bytes, ARLEN(bytes) ) != rtl_Random_E_None) {
        throw RuntimeException( OUSTR("random pool error!?"), 0 );
    }
    ::rtl::OUStringBuffer buf;
    for ( sal_uInt32 i = 0; i < ARLEN(bytes); ++i ) {
        buf.append( static_cast<sal_Int32>(bytes[ i ]), 0x10 );
    }
    return buf.makeStringAndClear();
}

//==============================================================================
Reference<XInterface> resolveUnoURL(
    OUString const & connectString,
    Reference<XComponentContext> const & xLocalContext,
    AbortChannel * abortChannel )
{
    Reference<bridge::XUnoUrlResolver> xUnoUrlResolver(
        bridge::UnoUrlResolver::create( xLocalContext ) );

    for (;;)
    {
        if (abortChannel != 0 && abortChannel->isAborted()) {
            throw ucb::CommandAbortedException(
                OUSTR("abort!"), Reference<XInterface>() );
        }
        try {
            return xUnoUrlResolver->resolve( connectString );
        }
        catch (connection::NoConnectException &) {
            TimeValue tv = { 0 /* secs */, 500000000 /* nanosecs */ };
            ::osl::Thread::wait( tv );
        }
    }
}

}
<|endoftext|>