<commit_before>/*
Copyright 2015 University of Auckland

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.Some license of other
*/

#include "gtest/gtest.h"

#include <libcellml>

TEST(Variable, serialise) {
    const std::string e = "<variable/>";
    libcellml::Variable v;
    std::string a = v.serialise(libcellml::FORMAT_XML);
    EXPECT_EQ(e, a);
}

TEST(Variable, setValidVariableName) {
    const std::string in = "valid_name";
    const std::string e = "<variable name=\"" + in + "\"/>";
    libcellml::Variable v;
    v.setName(in);
    std::string a = v.serialise(libcellml::FORMAT_XML);
    EXPECT_EQ(e, a);
}

TEST(Variable, setInvalidVariableName) {
    const std::string in = "invalid name";
    const std::string e = "<variable name=\"" + in + "\"/>";
    libcellml::Variable v;
    v.setName(in);
    std::string a = v.serialise(libcellml::FORMAT_XML);
    EXPECT_EQ(e, a);
}

TEST(Variable, getValidVariableName) {
    const std::string in = "valid_name";
    const std::string e = in;
    libcellml::Variable v;
    v.setName(in);
    std::string a = v.getName();
    EXPECT_EQ(e, a);
}

TEST(Variable, getInvalidVariableName) {
    const std::string in = "invalid name";
    const std::string e = in;
    libcellml::Variable v;
    v.setName(in);
    std::string a = v.getName();
    EXPECT_EQ(e, a);
}

TEST(Variable, setUnits) {
    const std::string in = "dimensionless";
    const std::string e = "<variable units=\"" + in + "\"/>";
    libcellml::Variable v;

    libcellml::UnitsPtr u = std::make_shared<libcellml::Units>();
    u->setName(in);
    v.setUnits(u);

    std::string a = v.serialise(libcellml::FORMAT_XML);
    EXPECT_EQ(e, a);
}

TEST(Variable, setUnitsAndName) {
    const std::string in = "valid_name";
    const std::string e = "<variable name=\"" + in + "\" units=\"dimensionless\"/>";
    libcellml::Variable v;
    v.setName(in);

    libcellml::UnitsPtr u = std::make_shared<libcellml::Units>();
    u->setName("dimensionless");
    v.setUnits(u);

    std::string a = v.serialise(libcellml::FORMAT_XML);
    EXPECT_EQ(e, a);
}

TEST(Variable, addVariable) {
    const std::string in = "valid_name";
    const std::string e =
            "<component name=\"" + in + "\">"
                "<variable name=\"" + in + "\" units=\"dimensionless\"/>"
              "</component>";

    libcellml::Component c;
    c.setName(in);

    libcellml::VariablePtr v = std::make_shared<libcellml::Variable>();
    v->setName(in);
    c.addVariable(v);

    libcellml::UnitsPtr u = std::make_shared<libcellml::Units>();
    u->setName("dimensionless");
    v->setUnits(u);

    std::string a = c.serialise(libcellml::FORMAT_XML);
    EXPECT_EQ(e, a);
}

TEST(Variable, addTwoVariables) {
    const std::string in = "valid_name";
    const std::string e =
            "<component name=\"" + in + "\">"
                "<variable name=\"variable1\"/>"
                "<variable name=\"variable2\"/>"
            "</component>";

    libcellml::Component c;
    c.setName(in);

    libcellml::VariablePtr v1 = std::make_shared<libcellml::Variable>();
    v1->setName("variable1");
    c.addVariable(v1);

    libcellml::VariablePtr v2 = std::make_shared<libcellml::Variable>();
    v2->setName("variable2");
    c.addVariable(v2);

    std::string a = c.serialise(libcellml::FORMAT_XML);
    EXPECT_EQ(e, a);
}

TEST(Variable, removeVariable) {
    const std::string in = "valid_name";
    const std::string e =
            "<component name=\"" + in + "\">"
                "<variable name=\"variable2\"/>"
            "</component>";

    libcellml::Component c;
    c.setName(in);

    libcellml::VariablePtr v1 = std::make_shared<libcellml::Variable>();
    v1->setName("variable1");
    c.addVariable(v1);

    libcellml::VariablePtr v2 = std::make_shared<libcellml::Variable>();
    v2->setName("variable2");
    c.addVariable(v2);

    c.removeVariable("variable1");
    std::string a = c.serialise(libcellml::FORMAT_XML);
    EXPECT_EQ(e, a);

    EXPECT_THROW(c.removeVariable("BAD_NAME"), std::out_of_range);
}

TEST(Variable, getVariableMethods) {
    const std::string in = "valid_name";
    libcellml::Component c;
    c.setName(in);

    libcellml::VariablePtr v1 = std::make_shared<libcellml::Variable>();
    v1->setName("variable1");
    c.addVariable(v1);
    libcellml::VariablePtr v2 = std::make_shared<libcellml::Variable>();
    v2->setName("variable2");
    c.addVariable(v2);
    libcellml::VariablePtr v3 = std::make_shared<libcellml::Variable>();
    v3->setName("variable3");
    c.addVariable(v3);
    libcellml::VariablePtr v4 = std::make_shared<libcellml::Variable>();
    v4->setName("variable4");
    c.addVariable(v4);

    // Get by string
    libcellml::VariablePtr vMethod1 = c.getVariable("variable1");
    std::string a1 = vMethod1->getName();
    EXPECT_EQ("variable1", a1);

    // Get by index
    libcellml::VariablePtr vMethod2 = c.getVariable(1);
    std::string a2 = vMethod2->getName();
    EXPECT_EQ("variable2", a2);

    // Get const by string
    const libcellml::VariablePtr vMethod3 = static_cast<const libcellml::Component>(c).getVariable("variable3");
    std::string a3 = vMethod3->getName();
    EXPECT_EQ("variable3", a3);

    // Get const by index
    const libcellml::VariablePtr vMethod4 = static_cast<const libcellml::Component>(c).getVariable(3);
    std::string a4 = vMethod4->getName();
    EXPECT_EQ("variable4", a4);
}

TEST(Variable, modelValidVariableName) {
    const std::string in = "valid_name";
    const std::string e =
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
            "<model xmlns=\"http://www.cellml.org/cellml/1.2#\">"
              "<component name=\"" + in + "\">"
                "<variable name=\"" + in + "\" units=\"dimensionless\"/>"
              "</component>"
            "</model>";

    libcellml::Model m;

    libcellml::ComponentPtr c = std::make_shared<libcellml::Component>();
    c->setName(in);
    m.addComponent(c);

    libcellml::VariablePtr v = std::make_shared<libcellml::Variable>();
    v->setName(in);
    c->addVariable(v);

    libcellml::UnitsPtr u = std::make_shared<libcellml::Units>();
    u->setName("dimensionless");
    v->setUnits(u);

    std::string a = m.serialise(libcellml::FORMAT_XML);
    EXPECT_EQ(e, a);
    EXPECT_EQ("valid_name", v->getName());
}

TEST(Variable, modelInvalidVariableName) {
    const std::string in = "invalid name";
    const std::string e =
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
            "<model xmlns=\"http://www.cellml.org/cellml/1.2#\">"
              "<component name=\"" + in + "\">"
                "<variable name=\"" + in + "\" units=\"dimensionless\"/>"
              "</component>"
            "</model>";

    libcellml::Model m;

    libcellml::ComponentPtr c = std::make_shared<libcellml::Component>();
    c->setName(in);
    m.addComponent(c);

    libcellml::VariablePtr v = std::make_shared<libcellml::Variable>();
    v->setName(in);
    c->addVariable(v);

    libcellml::UnitsPtr u = std::make_shared<libcellml::Units>();
    u->setName("dimensionless");
    v->setUnits(u);

    std::string a = m.serialise(libcellml::FORMAT_XML);
    EXPECT_EQ(e, a);
    EXPECT_EQ("invalid name", v->getName());
}

TEST(Variable, modelInvalidUnitsName) {
    const std::string in = "valid_name";
    const std::string e =
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
            "<model xmlns=\"http://www.cellml.org/cellml/1.2#\">"
              "<component name=\"" + in + "\">"
                "<variable name=\"" + in + "\" units=\"invalid name\"/>"
              "</component>"
            "</model>";

    libcellml::Model m;

    libcellml::ComponentPtr c = std::make_shared<libcellml::Component>();
    c->setName(in);
    m.addComponent(c);

    libcellml::VariablePtr v = std::make_shared<libcellml::Variable>();
    v->setName(in);
    c->addVariable(v);

    libcellml::UnitsPtr u = std::make_shared<libcellml::Units>();
    u->setName("invalid name");
    v->setUnits(u);

    std::string a = m.serialise(libcellml::FORMAT_XML);
    EXPECT_EQ(e, a);
    EXPECT_EQ("invalid name", u->getName());
}

<commit_msg>add tests for variable initial values<commit_after>/*
Copyright 2015 University of Auckland

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.Some license of other
*/

#include "gtest/gtest.h"

#include <libcellml>

TEST(Variable, serialise) {
    const std::string e = "<variable/>";
    libcellml::Variable v;
    std::string a = v.serialise(libcellml::FORMAT_XML);
    EXPECT_EQ(e, a);
}

TEST(Variable, setValidVariableName) {
    const std::string in = "valid_name";
    const std::string e = "<variable name=\"" + in + "\"/>";
    libcellml::Variable v;
    v.setName(in);
    std::string a = v.serialise(libcellml::FORMAT_XML);
    EXPECT_EQ(e, a);
}

TEST(Variable, setInvalidVariableName) {
    const std::string in = "invalid name";
    const std::string e = "<variable name=\"" + in + "\"/>";
    libcellml::Variable v;
    v.setName(in);
    std::string a = v.serialise(libcellml::FORMAT_XML);
    EXPECT_EQ(e, a);
}

TEST(Variable, getValidVariableName) {
    const std::string in = "valid_name";
    const std::string e = in;
    libcellml::Variable v;
    v.setName(in);
    std::string a = v.getName();
    EXPECT_EQ(e, a);
}

TEST(Variable, getInvalidVariableName) {
    const std::string in = "invalid name";
    const std::string e = in;
    libcellml::Variable v;
    v.setName(in);
    std::string a = v.getName();
    EXPECT_EQ(e, a);
}

TEST(Variable, setUnits) {
    const std::string in = "dimensionless";
    const std::string e = "<variable units=\"" + in + "\"/>";
    libcellml::Variable v;

    libcellml::UnitsPtr u = std::make_shared<libcellml::Units>();
    u->setName(in);
    v.setUnits(u);

    std::string a = v.serialise(libcellml::FORMAT_XML);
    EXPECT_EQ(e, a);
}

TEST(Variable, setUnitsAndName) {
    const std::string in = "valid_name";
    const std::string e = "<variable name=\"" + in + "\" units=\"dimensionless\"/>";
    libcellml::Variable v;
    v.setName(in);

    libcellml::UnitsPtr u = std::make_shared<libcellml::Units>();
    u->setName("dimensionless");
    v.setUnits(u);

    std::string a = v.serialise(libcellml::FORMAT_XML);
    EXPECT_EQ(e, a);
}

TEST(Variable, setInitialValue) {
    const std::string e = "<variable initial_value=\"0\"/>";
    libcellml::Variable v;
    v.setInitialValue(0.0);
    std::string a = v.serialise(libcellml::FORMAT_XML);
    EXPECT_EQ(e, a);
}

TEST(Variable, setInitialValueByRef) {
    const std::string e = "<variable initial_value=\"1.1\"/>";
    libcellml::VariablePtr v1 = std::make_shared<libcellml::Variable>();
    v1->setInitialValue(1.1);
    libcellml::Variable v2;
    v2.setInitialValue(v1);
    std::string a = v2.serialise(libcellml::FORMAT_XML);
    EXPECT_EQ(e, a);
}

TEST(Variable, getUnsetInitialValue) {
    libcellml::Variable v;
    EXPECT_THROW(v.getInitialValue(), std::out_of_range);
}

TEST(Variable, getSetInitialValue) {
    libcellml::Variable v;
    double e = 0.0;
    v.setInitialValue(e);
    double a = v.getInitialValue();
    EXPECT_EQ(e, a);
}

TEST(Variable, addVariable) {
    const std::string in = "valid_name";
    const std::string e =
            "<component name=\"" + in + "\">"
                "<variable name=\"" + in + "\" units=\"dimensionless\"/>"
              "</component>";

    libcellml::Component c;
    c.setName(in);

    libcellml::VariablePtr v = std::make_shared<libcellml::Variable>();
    v->setName(in);
    c.addVariable(v);

    libcellml::UnitsPtr u = std::make_shared<libcellml::Units>();
    u->setName("dimensionless");
    v->setUnits(u);

    std::string a = c.serialise(libcellml::FORMAT_XML);
    EXPECT_EQ(e, a);
}

TEST(Variable, addTwoVariables) {
    const std::string in = "valid_name";
    const std::string e =
            "<component name=\"" + in + "\">"
                "<variable name=\"variable1\"/>"
                "<variable name=\"variable2\"/>"
            "</component>";

    libcellml::Component c;
    c.setName(in);

    libcellml::VariablePtr v1 = std::make_shared<libcellml::Variable>();
    v1->setName("variable1");
    c.addVariable(v1);

    libcellml::VariablePtr v2 = std::make_shared<libcellml::Variable>();
    v2->setName("variable2");
    c.addVariable(v2);

    std::string a = c.serialise(libcellml::FORMAT_XML);
    EXPECT_EQ(e, a);
}

TEST(Variable, twoInitialisedVariables) {
    const std::string in = "valid_name";
    const std::string e =
            "<component name=\"" + in + "\">"
                "<variable initial_value=\"1\"/>"
                "<variable initial_value=\"-1\"/>"
            "</component>";

    libcellml::Component c;
    c.setName(in);

    libcellml::VariablePtr v1 = std::make_shared<libcellml::Variable>();
    v1->setInitialValue(1.0);
    c.addVariable(v1);

    libcellml::VariablePtr v2 = std::make_shared<libcellml::Variable>();
    v2->setInitialValue(-1.0);
    c.addVariable(v2);

    std::string a = c.serialise(libcellml::FORMAT_XML);
    EXPECT_EQ(e, a);
}

TEST(Variable, removeVariable) {
    const std::string in = "valid_name";
    const std::string e =
            "<component name=\"" + in + "\">"
                "<variable name=\"variable2\"/>"
            "</component>";

    libcellml::Component c;
    c.setName(in);

    libcellml::VariablePtr v1 = std::make_shared<libcellml::Variable>();
    v1->setName("variable1");
    c.addVariable(v1);

    libcellml::VariablePtr v2 = std::make_shared<libcellml::Variable>();
    v2->setName("variable2");
    c.addVariable(v2);

    c.removeVariable("variable1");
    std::string a = c.serialise(libcellml::FORMAT_XML);
    EXPECT_EQ(e, a);

    EXPECT_THROW(c.removeVariable("BAD_NAME"), std::out_of_range);
}

TEST(Variable, getVariableMethods) {
    const std::string in = "valid_name";
    libcellml::Component c;
    c.setName(in);

    libcellml::VariablePtr v1 = std::make_shared<libcellml::Variable>();
    v1->setName("variable1");
    c.addVariable(v1);
    libcellml::VariablePtr v2 = std::make_shared<libcellml::Variable>();
    v2->setName("variable2");
    c.addVariable(v2);
    libcellml::VariablePtr v3 = std::make_shared<libcellml::Variable>();
    v3->setName("variable3");
    c.addVariable(v3);
    libcellml::VariablePtr v4 = std::make_shared<libcellml::Variable>();
    v4->setName("variable4");
    c.addVariable(v4);

    // Get by string
    libcellml::VariablePtr vMethod1 = c.getVariable("variable1");
    std::string a1 = vMethod1->getName();
    EXPECT_EQ("variable1", a1);

    // Get by index
    libcellml::VariablePtr vMethod2 = c.getVariable(1);
    std::string a2 = vMethod2->getName();
    EXPECT_EQ("variable2", a2);

    // Get const by string
    const libcellml::VariablePtr vMethod3 = static_cast<const libcellml::Component>(c).getVariable("variable3");
    std::string a3 = vMethod3->getName();
    EXPECT_EQ("variable3", a3);

    // Get const by index
    const libcellml::VariablePtr vMethod4 = static_cast<const libcellml::Component>(c).getVariable(3);
    std::string a4 = vMethod4->getName();
    EXPECT_EQ("variable4", a4);
}

TEST(Variable, modelValidVariableName) {
    const std::string in = "valid_name";
    const std::string e =
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
            "<model xmlns=\"http://www.cellml.org/cellml/1.2#\">"
              "<component name=\"" + in + "\">"
                "<variable name=\"" + in + "\" units=\"dimensionless\"/>"
              "</component>"
            "</model>";

    libcellml::Model m;

    libcellml::ComponentPtr c = std::make_shared<libcellml::Component>();
    c->setName(in);
    m.addComponent(c);

    libcellml::VariablePtr v = std::make_shared<libcellml::Variable>();
    v->setName(in);
    c->addVariable(v);

    libcellml::UnitsPtr u = std::make_shared<libcellml::Units>();
    u->setName("dimensionless");
    v->setUnits(u);

    std::string a = m.serialise(libcellml::FORMAT_XML);
    EXPECT_EQ(e, a);
    EXPECT_EQ("valid_name", v->getName());
}

TEST(Variable, modelInvalidVariableName) {
    const std::string in = "invalid name";
    const std::string e =
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
            "<model xmlns=\"http://www.cellml.org/cellml/1.2#\">"
              "<component name=\"" + in + "\">"
                "<variable name=\"" + in + "\" units=\"dimensionless\"/>"
              "</component>"
            "</model>";

    libcellml::Model m;

    libcellml::ComponentPtr c = std::make_shared<libcellml::Component>();
    c->setName(in);
    m.addComponent(c);

    libcellml::VariablePtr v = std::make_shared<libcellml::Variable>();
    v->setName(in);
    c->addVariable(v);

    libcellml::UnitsPtr u = std::make_shared<libcellml::Units>();
    u->setName("dimensionless");
    v->setUnits(u);

    std::string a = m.serialise(libcellml::FORMAT_XML);
    EXPECT_EQ(e, a);
    EXPECT_EQ("invalid name", v->getName());
}

TEST(Variable, modelInvalidUnitsName) {
    const std::string in = "valid_name";
    const std::string e =
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
            "<model xmlns=\"http://www.cellml.org/cellml/1.2#\">"
              "<component name=\"" + in + "\">"
                "<variable name=\"" + in + "\" units=\"invalid name\"/>"
              "</component>"
            "</model>";

    libcellml::Model m;

    libcellml::ComponentPtr c = std::make_shared<libcellml::Component>();
    c->setName(in);
    m.addComponent(c);

    libcellml::VariablePtr v = std::make_shared<libcellml::Variable>();
    v->setName(in);
    c->addVariable(v);

    libcellml::UnitsPtr u = std::make_shared<libcellml::Units>();
    u->setName("invalid name");
    v->setUnits(u);

    std::string a = m.serialise(libcellml::FORMAT_XML);
    EXPECT_EQ(e, a);
    EXPECT_EQ("invalid name", u->getName());
}

TEST(Variable, modelTwoNamedInitialisedVariables) {
    const std::string in = "valid_name";
    const std::string e =
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
            "<model xmlns=\"http://www.cellml.org/cellml/1.2#\">"
                "<component name=\"" + in + "\">"
                    "<variable name=\"variable1\" initial_value=\"1\"/>"
                    "<variable name=\"variable2\" initial_value=\"-1\"/>"
                "</component>"
            "</model>";

    libcellml::Model m;

    libcellml::ComponentPtr c = std::make_shared<libcellml::Component>();
    c->setName(in);
    m.addComponent(c);

    libcellml::VariablePtr v1 = std::make_shared<libcellml::Variable>();
    v1->setName("variable1");
    v1->setInitialValue(1.0);
    c->addVariable(v1);

    libcellml::VariablePtr v2 = std::make_shared<libcellml::Variable>();
    v2->setName("variable2");
    v2->setInitialValue(-1.0);
    c->addVariable(v2);

    std::string a = m.serialise(libcellml::FORMAT_XML);
    EXPECT_EQ(e, a);
}

<|endoftext|>


<commit_before>/*
 * Copyright (C) 2010, 2011, Gostai S.A.S.
 *
 * This software is provided "as is" without warranty of any kind,
 * either expressed or implied, including but not limited to the
 * implied warranties of fitness for a particular purpose.
 *
 * See the LICENSE file for more information.
 */

#include <libport/cmath>
#include <libport/format.hh>
#include "callbacks-caller.hh"

jfieldID CallbacksCaller::ulist_swigptr_id = 0;
jfieldID CallbacksCaller::uimage_swigptr_id = 0;
jfieldID CallbacksCaller::usound_swigptr_id = 0;
jfieldID CallbacksCaller::udictionary_swigptr_id = 0;
jfieldID CallbacksCaller::ubinary_swigptr_id = 0;
jfieldID CallbacksCaller::uvalue_swigptr_id = 0;
jfieldID CallbacksCaller::uvar_swigptr_id = 0;
jclass CallbacksCaller::uobject_cls = 0;
jfieldID CallbacksCaller::uobject_swigptr_id = 0;
jmethodID CallbacksCaller::class_getname_id = 0;
jclass CallbacksCaller::class_cls = 0;
bool CallbacksCaller::jni_variables_cached_ = false;

CallbacksCaller::CallbacksCaller()
  : mid(0)
  , obj(0)
  , jvm(0)
  , env_(0)
{}

int
CallbacksCaller::callNotifyChangeInt_0()
{
  if (!init_env())
    return 0;
  int res = env_->CallIntMethod(obj, mid);
  testForException();
  return res;
}

int
CallbacksCaller::callNotifyChangeInt_1(urbi::UVar& v)
{
  if (!init_env())
    return 0;
  jvalue obj1 = arg_convert[0]->convert(env_, v);
  jvalue arg[] = { obj1 };
  int res = env_->CallIntMethodA(obj, mid, arg);
  testForException();
  return res;
}

void
CallbacksCaller::callNotifyChangeVoid_0()
{
  if (!init_env())
    return;
  env_->CallVoidMethod(obj, mid);
  testForException();
}

void
CallbacksCaller::callNotifyChangeVoid_1(urbi::UVar& v)
{
  if (!init_env())
    return;
  jvalue obj1 = arg_convert[0]->convert(env_, v);
  jvalue arg[] = { obj1 };
  env_->CallVoidMethodA(obj, mid, arg);
  testForException();

}

bool
CallbacksCaller::init_env()
{
  if (!env_ || !jvm)
  {
    jsize size;
    JNI_GetCreatedJavaVMs(&jvm, 1, &size);
    if (!size)
    {
      std::cerr << "Error retrivieving created JavaVMs." << std::endl;
      return false;
    }
  }
  jvm->AttachCurrentThread((void**) &env_, 0);

  if (!env_)
  {
    std::cerr << "Error retrivieving JNIEnv pointer." << std::endl;
    return false;
  }
  return true;
}

void
CallbacksCaller::setObject(jobject o)
{
  obj = o;
}

void
CallbacksCaller::setMethodID(jmethodID id)
{
  mid = id;
}

bool
CallbacksCaller::areJNIVariablesCached()
{
  return jni_variables_cached_;
}

bool
CallbacksCaller::cacheJNIVariables(JNIEnv* env)
{

  INIT_CONVERTERS_STATIC_ATTRS(env);

#define CLEAN_AND_THROW(Msg)			\
  do						\
  {						\
    FRAISE(Msg);                                \
    return false;				\
  } while (false)

  /// Get UValue swigCPtr attribute id
  if (!(uvalue_swigptr_id = env->GetFieldID(UValueConverter::cls, "swigCPtr", "J")))
    CLEAN_AND_THROW("Can't find UValue swigCPtr");

  /// Get UList swigCPtr attribute id
  if (!(ulist_swigptr_id = env->GetFieldID(UListConverter::cls, "swigCPtr", "J")))
    CLEAN_AND_THROW("Can't find UList swigCPtr");

  /// Get UImage swigCPtr attribute id
  if (!(uimage_swigptr_id = env->GetFieldID(UImageConverter::cls, "swigCPtr", "J")))
    CLEAN_AND_THROW("Can't find UImage swigCPtr");

  /// Get UBinary swigCPtr attribute id
  if (!(ubinary_swigptr_id = env->GetFieldID(UBinaryConverter::cls, "swigCPtr", "J")))
    CLEAN_AND_THROW("Can't find UBinary swigCPtr");

  /// Get Usound swigCPtr attribute id
  if (!(usound_swigptr_id = env->GetFieldID(USoundConverter::cls, "swigCPtr", "J")))
    CLEAN_AND_THROW("Can't find USound swigCPtr");

  /// Get Udictionary swigCPtr attribute id
  if (!(udictionary_swigptr_id = env->GetFieldID(UDictionaryConverter::cls, "swigCPtr", "J")))
    CLEAN_AND_THROW("Can't find UDictionary swigCPtr");

  /// Get UValue swigCPtr attribute id
  if (!(uvar_swigptr_id = env->GetFieldID(UVarConverter::cls, "swigCPtr", "J")))
    CLEAN_AND_THROW("Can't find UVar swigCPtr");

  /// Get the jclass for UObject
  if (!(uobject_cls = getGlobalRef(env, "urbi/UObjectCPP")))
    CLEAN_AND_THROW("Can't find UObject class");

  /// Get UObject swigCPtr attribute id
  if (!(uobject_swigptr_id = env->GetFieldID(uobject_cls, "swigCPtr", "J")))
    CLEAN_AND_THROW("Can't find UObject swigCPtr");

  /// Get the jclass for Class
  if (!(class_cls = getGlobalRef(env, "java/lang/Class")))
    CLEAN_AND_THROW("Can't find Class class");

  /// Get String (char) Constructor id
  if (!(class_getname_id = env->GetMethodID(class_cls, "getName", "()Ljava/lang/String;")))
    CLEAN_AND_THROW("Can't find Class getName function");

#undef CLEAN_AND_THROW

  jni_variables_cached_ = true;
  return true; /// all went OK
}

jclass
CallbacksCaller::getGlobalRef(JNIEnv* env, const char* classname)
{
  /// Get the jclass for UValue
  jclass tmp, res;
  if (!(tmp = env->FindClass(classname)))
    FRAISE("Can't find class %s", classname);

  if (!(res = (jclass) env->NewGlobalRef(tmp)))
    FRAISE("Can't create Global Ref for class %s", classname);

  env->DeleteLocalRef(tmp);
  return res;
}

urbi::UObject*
CallbacksCaller::getUObjectFromObject(jobject obj, JNIEnv* env)
{
  if (obj)
  {
    jlong ptr = env->GetLongField(obj, uobject_swigptr_id);
    if (ptr)  /// Java alocated memory, prefer allocate mine
      return (urbi::UObject*) ptr;
    else
      return 0;
  }
  else
    return 0;
}

urbi::UVar*
CallbacksCaller::getUVarFromObject(jobject obj)
{
  if (obj)
  {
    jlong ptr = env_->GetLongField(obj, uobject_swigptr_id);
    if (ptr)  /// Java alocated memory, prefer allocate mine
      return (urbi::UVar*) ptr;
    else
      return 0;
  }
  else
    return 0;
}

urbi::UValue
CallbacksCaller::getUValueFromObject(jobject obj)
{
  if (obj)
  {
    jlong ptr = env_->GetLongField(obj, uvalue_swigptr_id);
    if (ptr)  /// Java alocated memory, prefer allocate mine
      return *(urbi::UValue*) ptr;
    else
      return urbi::UValue();
  }
  else
    return urbi::UValue();
}

urbi::UDictionary
CallbacksCaller::getUDictionaryFromObject(jobject obj)
{
  if (obj)
  {
    jlong ptr = env_->GetLongField(obj, udictionary_swigptr_id);
    if (ptr)  /// Java alocated memory, prefer allocate mine
      return *(urbi::UDictionary*) ptr;
    else
      return urbi::UDictionary();
  }
  else
    return urbi::UDictionary();
}

urbi::UBinary
CallbacksCaller::getUBinaryFromObject(jobject obj)
{
  if (obj)
  {
    jlong ptr = env_->GetLongField(obj, ubinary_swigptr_id);
    if (ptr)  /// Java alocated memory, prefer allocate mine
      return *(urbi::UBinary*) ptr;
    else
      return urbi::UBinary();
  }
  else
    return urbi::UBinary();
}

urbi::UImage
CallbacksCaller::getUImageFromObject(jobject obj)
{
  if (obj)
  {
    jlong ptr = env_->GetLongField(obj, uimage_swigptr_id);
    if (ptr)  /// Java alocated memory, prefer allocate mine
      return *(urbi::UImage*) ptr;
    else
      return urbi::UImage();
  }
  else
    return urbi::UImage();
}

urbi::USound
CallbacksCaller::getUSoundFromObject(jobject obj)
{
  if (obj)
  {
    jlong ptr = env_->GetLongField(obj, usound_swigptr_id);
    if (ptr)  /// Java alocated memory, prefer allocate mine
      return *(urbi::USound*) ptr;
    else
      return urbi::USound();
  }
  else
    return urbi::USound();
}

urbi::UList
CallbacksCaller::getUListFromObject(jobject obj)
{
  if (obj)
  {
    jlong ptr = env_->GetLongField(obj, ulist_swigptr_id);
    if (ptr)  /// Java alocated memory, prefer allocate mine
      return *(urbi::UList*) ptr;
    else
      return urbi::UList();
  }
  else
    return urbi::UList();
}

std::string
CallbacksCaller::getStringFromJString(jstring obj)
{
  char const* str = env_->GetStringUTFChars(obj, 0);
  std::string res = str;
  env_->ReleaseStringUTFChars(obj, str);
  return res;
}

void
CallbacksCaller::testForException()
{
  jthrowable exc = env_->ExceptionOccurred();
  if (exc)
  {
    env_->ExceptionDescribe();
    env_->ExceptionClear();
    jclass java_class = env_->GetObjectClass(exc);
    assert(java_class);
    jmethodID getMessage = env_->GetMethodID(java_class,
					     "getMessage",
					     "()Ljava/lang/String;");
    assert(getMessage);
    jstring message =
      static_cast<jstring>(env_->CallObjectMethod(exc, getMessage));
    assert(message);
    char const* utfMessage = env_->GetStringUTFChars(message, 0);
    jstring name =
      static_cast<jstring>(env_->CallObjectMethod(java_class, class_getname_id));
    assert(name);
    char const* utfName = env_->GetStringUTFChars(name, 0);
    std::string m = utfMessage;
    std::string n = utfName;
    env_->ReleaseStringUTFChars(message, utfMessage);
    env_->ReleaseStringUTFChars(name, utfName);
    FRAISE("%s: %s", n, m);
  }
};

void
SWIG_JavaThrowException(JNIEnv *jenv,
			SWIG_JavaExceptionCodes code,
			const char *msg)
{
  jclass excep;
  static const SWIG_JavaExceptions_t java_exceptions[] =
  {
    { SWIG_JavaOutOfMemoryError, "java/lang/OutOfMemoryError" },
    { SWIG_JavaIOException, "java/io/IOException" },
    { SWIG_JavaRuntimeException, "java/lang/RuntimeException" },
    { SWIG_JavaIndexOutOfBoundsException, "java/lang/IndexOutOfBoundsException" },
    { SWIG_JavaArithmeticException, "java/lang/ArithmeticException" },
    { SWIG_JavaIllegalArgumentException, "java/lang/IllegalArgumentException" },
    { SWIG_JavaNullPointerException, "java/lang/NullPointerException" },
    { SWIG_JavaDirectorPureVirtual, "java/lang/RuntimeException" },
    { SWIG_JavaUnknownError,  "java/lang/UnknownError" },
    { (SWIG_JavaExceptionCodes)0,  "java/lang/UnknownError" }
  };

  const SWIG_JavaExceptions_t *except_ptr = java_exceptions;
  while (except_ptr->code != code && except_ptr->code)
    except_ptr++;

  jenv->ExceptionClear();
  excep = jenv->FindClass(except_ptr->java_exception);

  if (excep)
    jenv->ThrowNew(excep, msg);
}
<commit_msg>Java: factor.<commit_after>/*
 * Copyright (C) 2010, 2011, Gostai S.A.S.
 *
 * This software is provided "as is" without warranty of any kind,
 * either expressed or implied, including but not limited to the
 * implied warranties of fitness for a particular purpose.
 *
 * See the LICENSE file for more information.
 */

#include <libport/cmath>
#include <libport/format.hh>
#include "callbacks-caller.hh"

jfieldID CallbacksCaller::ulist_swigptr_id = 0;
jfieldID CallbacksCaller::uimage_swigptr_id = 0;
jfieldID CallbacksCaller::usound_swigptr_id = 0;
jfieldID CallbacksCaller::udictionary_swigptr_id = 0;
jfieldID CallbacksCaller::ubinary_swigptr_id = 0;
jfieldID CallbacksCaller::uvalue_swigptr_id = 0;
jfieldID CallbacksCaller::uvar_swigptr_id = 0;
jclass CallbacksCaller::uobject_cls = 0;
jfieldID CallbacksCaller::uobject_swigptr_id = 0;
jmethodID CallbacksCaller::class_getname_id = 0;
jclass CallbacksCaller::class_cls = 0;
bool CallbacksCaller::jni_variables_cached_ = false;

CallbacksCaller::CallbacksCaller()
  : mid(0)
  , obj(0)
  , jvm(0)
  , env_(0)
{}

int
CallbacksCaller::callNotifyChangeInt_0()
{
  if (!init_env())
    return 0;
  int res = env_->CallIntMethod(obj, mid);
  testForException();
  return res;
}

int
CallbacksCaller::callNotifyChangeInt_1(urbi::UVar& v)
{
  if (!init_env())
    return 0;
  jvalue obj1 = arg_convert[0]->convert(env_, v);
  jvalue arg[] = { obj1 };
  int res = env_->CallIntMethodA(obj, mid, arg);
  testForException();
  return res;
}

void
CallbacksCaller::callNotifyChangeVoid_0()
{
  if (!init_env())
    return;
  env_->CallVoidMethod(obj, mid);
  testForException();
}

void
CallbacksCaller::callNotifyChangeVoid_1(urbi::UVar& v)
{
  if (!init_env())
    return;
  jvalue obj1 = arg_convert[0]->convert(env_, v);
  jvalue arg[] = { obj1 };
  env_->CallVoidMethodA(obj, mid, arg);
  testForException();

}

bool
CallbacksCaller::init_env()
{
  if (!env_ || !jvm)
  {
    jsize size;
    JNI_GetCreatedJavaVMs(&jvm, 1, &size);
    if (!size)
    {
      std::cerr << "Error retrivieving created JavaVMs." << std::endl;
      return false;
    }
  }
  jvm->AttachCurrentThread((void**) &env_, 0);

  if (!env_)
  {
    std::cerr << "Error retrivieving JNIEnv pointer." << std::endl;
    return false;
  }
  return true;
}

void
CallbacksCaller::setObject(jobject o)
{
  obj = o;
}

void
CallbacksCaller::setMethodID(jmethodID id)
{
  mid = id;
}

bool
CallbacksCaller::areJNIVariablesCached()
{
  return jni_variables_cached_;
}

bool
CallbacksCaller::cacheJNIVariables(JNIEnv* env)
{

  INIT_CONVERTERS_STATIC_ATTRS(env);

#define CASE(Type, Var)                                                 \
  if (!(Var ## _swigptr_id =                                            \
        env->GetFieldID(Type ## Converter::cls, "swigCPtr", "J")))      \
    FRAISE("Can't find %s swigCPtr", #Type)

  CASE(UBinary, ubinary);
  CASE(UDictionary, udictionary);
  CASE(UImage, uimage);
  CASE(UList, ulist);
  CASE(USound, usound);
  CASE(UValue, uvalue);
  CASE(UVar, uvar);
#undef CASE

  // Get the jclass for UObject
  if (!(uobject_cls = getGlobalRef(env, "urbi/UObjectCPP")))
    FRAISE("Can't find UObject class");

  // Get UObject swigCPtr attribute id
  if (!(uobject_swigptr_id = env->GetFieldID(uobject_cls, "swigCPtr", "J")))
    FRAISE("Can't find UObject swigCPtr");

  // Get the jclass for Class
  if (!(class_cls = getGlobalRef(env, "java/lang/Class")))
    FRAISE("Can't find Class class");

  // Get String (char) Constructor id
  if (!(class_getname_id =
        env->GetMethodID(class_cls, "getName", "()Ljava/lang/String;")))
    FRAISE("Can't find Class getName function");

  jni_variables_cached_ = true;
  return true; /// all went OK
}

jclass
CallbacksCaller::getGlobalRef(JNIEnv* env, const char* classname)
{
  /// Get the jclass for UValue
  jclass tmp, res;
  if (!(tmp = env->FindClass(classname)))
    FRAISE("Can't find class %s", classname);

  if (!(res = (jclass) env->NewGlobalRef(tmp)))
    FRAISE("Can't create Global Ref for class %s", classname);

  env->DeleteLocalRef(tmp);
  return res;
}

urbi::UObject*
CallbacksCaller::getUObjectFromObject(jobject obj, JNIEnv* env)
{
  if (obj)
  {
    jlong ptr = env->GetLongField(obj, uobject_swigptr_id);
    if (ptr)  /// Java alocated memory, prefer allocate mine
      return (urbi::UObject*) ptr;
    else
      return 0;
  }
  else
    return 0;
}

urbi::UVar*
CallbacksCaller::getUVarFromObject(jobject obj)
{
  if (obj)
  {
    jlong ptr = env_->GetLongField(obj, uobject_swigptr_id);
    if (ptr)  /// Java alocated memory, prefer allocate mine
      return (urbi::UVar*) ptr;
    else
      return 0;
  }
  else
    return 0;
}

urbi::UValue
CallbacksCaller::getUValueFromObject(jobject obj)
{
  if (obj)
  {
    jlong ptr = env_->GetLongField(obj, uvalue_swigptr_id);
    if (ptr)  /// Java alocated memory, prefer allocate mine
      return *(urbi::UValue*) ptr;
    else
      return urbi::UValue();
  }
  else
    return urbi::UValue();
}

urbi::UDictionary
CallbacksCaller::getUDictionaryFromObject(jobject obj)
{
  if (obj)
  {
    jlong ptr = env_->GetLongField(obj, udictionary_swigptr_id);
    if (ptr)  /// Java alocated memory, prefer allocate mine
      return *(urbi::UDictionary*) ptr;
    else
      return urbi::UDictionary();
  }
  else
    return urbi::UDictionary();
}

urbi::UBinary
CallbacksCaller::getUBinaryFromObject(jobject obj)
{
  if (obj)
  {
    jlong ptr = env_->GetLongField(obj, ubinary_swigptr_id);
    if (ptr)  /// Java alocated memory, prefer allocate mine
      return *(urbi::UBinary*) ptr;
    else
      return urbi::UBinary();
  }
  else
    return urbi::UBinary();
}

urbi::UImage
CallbacksCaller::getUImageFromObject(jobject obj)
{
  if (obj)
  {
    jlong ptr = env_->GetLongField(obj, uimage_swigptr_id);
    if (ptr)  /// Java alocated memory, prefer allocate mine
      return *(urbi::UImage*) ptr;
    else
      return urbi::UImage();
  }
  else
    return urbi::UImage();
}

urbi::USound
CallbacksCaller::getUSoundFromObject(jobject obj)
{
  if (obj)
  {
    jlong ptr = env_->GetLongField(obj, usound_swigptr_id);
    if (ptr)  /// Java alocated memory, prefer allocate mine
      return *(urbi::USound*) ptr;
    else
      return urbi::USound();
  }
  else
    return urbi::USound();
}

urbi::UList
CallbacksCaller::getUListFromObject(jobject obj)
{
  if (obj)
  {
    jlong ptr = env_->GetLongField(obj, ulist_swigptr_id);
    if (ptr)  /// Java alocated memory, prefer allocate mine
      return *(urbi::UList*) ptr;
    else
      return urbi::UList();
  }
  else
    return urbi::UList();
}

std::string
CallbacksCaller::getStringFromJString(jstring obj)
{
  char const* str = env_->GetStringUTFChars(obj, 0);
  std::string res = str;
  env_->ReleaseStringUTFChars(obj, str);
  return res;
}

void
CallbacksCaller::testForException()
{
  jthrowable exc = env_->ExceptionOccurred();
  if (exc)
  {
    env_->ExceptionDescribe();
    env_->ExceptionClear();
    jclass java_class = env_->GetObjectClass(exc);
    assert(java_class);
    jmethodID getMessage = env_->GetMethodID(java_class,
					     "getMessage",
					     "()Ljava/lang/String;");
    assert(getMessage);
    jstring message =
      static_cast<jstring>(env_->CallObjectMethod(exc, getMessage));
    assert(message);
    char const* utfMessage = env_->GetStringUTFChars(message, 0);
    jstring name =
      static_cast<jstring>(env_->CallObjectMethod(java_class, class_getname_id));
    assert(name);
    char const* utfName = env_->GetStringUTFChars(name, 0);
    std::string m = utfMessage;
    std::string n = utfName;
    env_->ReleaseStringUTFChars(message, utfMessage);
    env_->ReleaseStringUTFChars(name, utfName);
    FRAISE("%s: %s", n, m);
  }
};

void
SWIG_JavaThrowException(JNIEnv *jenv,
			SWIG_JavaExceptionCodes code,
			const char *msg)
{
  jclass excep;
  static const SWIG_JavaExceptions_t java_exceptions[] =
  {
    { SWIG_JavaOutOfMemoryError, "java/lang/OutOfMemoryError" },
    { SWIG_JavaIOException, "java/io/IOException" },
    { SWIG_JavaRuntimeException, "java/lang/RuntimeException" },
    { SWIG_JavaIndexOutOfBoundsException, "java/lang/IndexOutOfBoundsException" },
    { SWIG_JavaArithmeticException, "java/lang/ArithmeticException" },
    { SWIG_JavaIllegalArgumentException, "java/lang/IllegalArgumentException" },
    { SWIG_JavaNullPointerException, "java/lang/NullPointerException" },
    { SWIG_JavaDirectorPureVirtual, "java/lang/RuntimeException" },
    { SWIG_JavaUnknownError,  "java/lang/UnknownError" },
    { (SWIG_JavaExceptionCodes)0,  "java/lang/UnknownError" }
  };

  const SWIG_JavaExceptions_t *except_ptr = java_exceptions;
  while (except_ptr->code != code && except_ptr->code)
    except_ptr++;

  jenv->ExceptionClear();
  excep = jenv->FindClass(except_ptr->java_exception);

  if (excep)
    jenv->ThrowNew(excep, msg);
}
<|endoftext|>


<commit_before>//  Copyright (c) 2013, Facebook, Inc.  All rights reserved.
//  This source code is licensed under the BSD-style license found in the
//  LICENSE file in the root directory of this source tree. An additional grant
//  of patent rights can be found in the PATENTS file in the same directory.
//
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.

#include "db/flush_job.h"

#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif

#include <inttypes.h>
#include <algorithm>
#include <vector>

#include "db/builder.h"
#include "db/db_iter.h"
#include "db/dbformat.h"
#include "db/filename.h"
#include "db/log_reader.h"
#include "db/log_writer.h"
#include "db/memtable.h"
#include "db/memtable_list.h"
#include "db/merge_context.h"
#include "db/version_set.h"
#include "port/port.h"
#include "port/likely.h"
#include "rocksdb/db.h"
#include "rocksdb/env.h"
#include "rocksdb/statistics.h"
#include "rocksdb/status.h"
#include "rocksdb/table.h"
#include "table/block.h"
#include "table/block_based_table_factory.h"
#include "table/merger.h"
#include "table/table_builder.h"
#include "table/two_level_iterator.h"
#include "util/coding.h"
#include "util/logging.h"
#include "util/log_buffer.h"
#include "util/mutexlock.h"
#include "util/perf_context_imp.h"
#include "util/iostats_context_imp.h"
#include "util/stop_watch.h"
#include "util/sync_point.h"

namespace rocksdb {

FlushJob::FlushJob(const std::string& dbname, ColumnFamilyData* cfd,
                   const DBOptions& db_options,
                   const MutableCFOptions& mutable_cf_options,
                   const EnvOptions& env_options, VersionSet* versions,
                   port::Mutex* db_mutex, std::atomic<bool>* shutting_down,
                   FileNumToPathIdMap* pending_outputs,
                   SequenceNumber newest_snapshot, JobContext* job_context,
                   LogBuffer* log_buffer, Directory* db_directory,
                   CompressionType output_compression, Statistics* stats)
    : dbname_(dbname),
      cfd_(cfd),
      db_options_(db_options),
      mutable_cf_options_(mutable_cf_options),
      env_options_(env_options),
      versions_(versions),
      db_mutex_(db_mutex),
      shutting_down_(shutting_down),
      pending_outputs_(pending_outputs),
      newest_snapshot_(newest_snapshot),
      job_context_(job_context),
      log_buffer_(log_buffer),
      db_directory_(db_directory),
      output_compression_(output_compression),
      stats_(stats) {}

Status FlushJob::Run() {
  // Save the contents of the earliest memtable as a new Table
  uint64_t file_number;
  autovector<MemTable*> mems;
  cfd_->imm()->PickMemtablesToFlush(&mems);
  if (mems.empty()) {
    LogToBuffer(log_buffer_, "[%s] Nothing in memtable to flush",
                cfd_->GetName().c_str());
    return Status::OK();
  }

  // entries mems are (implicitly) sorted in ascending order by their created
  // time. We will use the first memtable's `edit` to keep the meta info for
  // this flush.
  MemTable* m = mems[0];
  VersionEdit* edit = m->GetEdits();
  edit->SetPrevLogNumber(0);
  // SetLogNumber(log_num) indicates logs with number smaller than log_num
  // will no longer be picked up for recovery.
  edit->SetLogNumber(mems.back()->GetNextLogNumber());
  edit->SetColumnFamily(cfd_->GetID());

  // This will release and re-acquire the mutex.
  Status s = WriteLevel0Table(mems, edit, &file_number);

  if (s.ok() &&
      (shutting_down_->load(std::memory_order_acquire) || cfd_->IsDropped())) {
    s = Status::ShutdownInProgress(
        "Database shutdown or Column family drop during flush");
  }

  if (!s.ok()) {
    cfd_->imm()->RollbackMemtableFlush(mems, file_number, pending_outputs_);
  } else {
    // Replace immutable memtable with the generated Table
    s = cfd_->imm()->InstallMemtableFlushResults(
        cfd_, mutable_cf_options_, mems, versions_, db_mutex_, file_number,
        pending_outputs_, &job_context_->memtables_to_free, db_directory_,
        log_buffer_);
  }

  return s;
}

Status FlushJob::WriteLevel0Table(const autovector<MemTable*>& mems,
                                  VersionEdit* edit, uint64_t* filenumber) {
  db_mutex_->AssertHeld();
  const uint64_t start_micros = db_options_.env->NowMicros();
  FileMetaData meta;

  meta.fd = FileDescriptor(versions_->NewFileNumber(), 0, 0);
  *filenumber = meta.fd.GetNumber();
  // path 0 for level 0 file.
  pending_outputs_->insert({meta.fd.GetNumber(), 0});

  const SequenceNumber earliest_seqno_in_memtable =
      mems[0]->GetFirstSequenceNumber();
  Version* base = cfd_->current();
  base->Ref();  // it is likely that we do not need this reference
  Status s;
  {
    db_mutex_->Unlock();
    if (log_buffer_) {
      log_buffer_->FlushBufferToLog();
    }
    std::vector<Iterator*> memtables;
    ReadOptions ro;
    ro.total_order_seek = true;
    Arena arena;
    for (MemTable* m : mems) {
      Log(db_options_.info_log,
          "[%s] Flushing memtable with next log file: %" PRIu64 "\n",
          cfd_->GetName().c_str(), m->GetNextLogNumber());
      memtables.push_back(m->NewIterator(ro, &arena));
    }
    {
      ScopedArenaIterator iter(NewMergingIterator(&cfd_->internal_comparator(),
                                                  &memtables[0],
                                                  memtables.size(), &arena));
      Log(db_options_.info_log,
          "[%s] Level-0 flush table #%" PRIu64 ": started",
          cfd_->GetName().c_str(), meta.fd.GetNumber());

      s = BuildTable(dbname_, db_options_.env, *cfd_->ioptions(), env_options_,
                     cfd_->table_cache(), iter.get(), &meta,
                     cfd_->internal_comparator(), newest_snapshot_,
                     earliest_seqno_in_memtable, output_compression_,
                     cfd_->ioptions()->compression_opts, Env::IO_HIGH);
      LogFlush(db_options_.info_log);
    }
    Log(db_options_.info_log,
        "[%s] Level-0 flush table #%" PRIu64 ": %" PRIu64 " bytes %s",
        cfd_->GetName().c_str(), meta.fd.GetNumber(), meta.fd.GetFileSize(),
        s.ToString().c_str());

    if (!db_options_.disableDataSync && db_directory_ != nullptr) {
      db_directory_->Fsync();
    }
    db_mutex_->Lock();
  }
  base->Unref();

  // re-acquire the most current version
  base = cfd_->current();

  // There could be multiple threads writing to its own level-0 file.
  // The pending_outputs cannot be cleared here, otherwise this newly
  // created file might not be considered as a live-file by another
  // compaction thread that is concurrently deleting obselete files.
  // The pending_outputs can be cleared only after the new version is
  // committed so that other threads can recognize this file as a
  // valid one.
  // pending_outputs_.erase(meta.number);

  // Note that if file_size is zero, the file has been deleted and
  // should not be added to the manifest.
  int level = 0;
  if (s.ok() && meta.fd.GetFileSize() > 0) {
    const Slice min_user_key = meta.smallest.user_key();
    const Slice max_user_key = meta.largest.user_key();
    // if we have more than 1 background thread, then we cannot
    // insert files directly into higher levels because some other
    // threads could be concurrently producing compacted files for
    // that key range.
    if (base != nullptr && db_options_.max_background_compactions <= 1 &&
        db_options_.max_background_flushes == 0 &&
        cfd_->ioptions()->compaction_style == kCompactionStyleLevel) {
      level = base->PickLevelForMemTableOutput(mutable_cf_options_,
                                               min_user_key, max_user_key);
    }
    edit->AddFile(level, meta.fd.GetNumber(), meta.fd.GetPathId(),
                  meta.fd.GetFileSize(), meta.smallest, meta.largest,
                  meta.smallest_seqno, meta.largest_seqno);
  }

  InternalStats::CompactionStats stats(1);
  stats.micros = db_options_.env->NowMicros() - start_micros;
  stats.bytes_written = meta.fd.GetFileSize();
  cfd_->internal_stats()->AddCompactionStats(level, stats);
  cfd_->internal_stats()->AddCFStats(InternalStats::BYTES_FLUSHED,
                                     meta.fd.GetFileSize());
  RecordTick(stats_, COMPACT_WRITE_BYTES, meta.fd.GetFileSize());
  return s;
}

}  // namespace rocksdb
<commit_msg>Apply InfoLogLevel to the logs in db/flush_job.cc<commit_after>//  Copyright (c) 2013, Facebook, Inc.  All rights reserved.
//  This source code is licensed under the BSD-style license found in the
//  LICENSE file in the root directory of this source tree. An additional grant
//  of patent rights can be found in the PATENTS file in the same directory.
//
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.

#include "db/flush_job.h"

#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif

#include <inttypes.h>
#include <algorithm>
#include <vector>

#include "db/builder.h"
#include "db/db_iter.h"
#include "db/dbformat.h"
#include "db/filename.h"
#include "db/log_reader.h"
#include "db/log_writer.h"
#include "db/memtable.h"
#include "db/memtable_list.h"
#include "db/merge_context.h"
#include "db/version_set.h"
#include "port/port.h"
#include "port/likely.h"
#include "rocksdb/db.h"
#include "rocksdb/env.h"
#include "rocksdb/statistics.h"
#include "rocksdb/status.h"
#include "rocksdb/table.h"
#include "table/block.h"
#include "table/block_based_table_factory.h"
#include "table/merger.h"
#include "table/table_builder.h"
#include "table/two_level_iterator.h"
#include "util/coding.h"
#include "util/logging.h"
#include "util/log_buffer.h"
#include "util/mutexlock.h"
#include "util/perf_context_imp.h"
#include "util/iostats_context_imp.h"
#include "util/stop_watch.h"
#include "util/sync_point.h"

namespace rocksdb {

FlushJob::FlushJob(const std::string& dbname, ColumnFamilyData* cfd,
                   const DBOptions& db_options,
                   const MutableCFOptions& mutable_cf_options,
                   const EnvOptions& env_options, VersionSet* versions,
                   port::Mutex* db_mutex, std::atomic<bool>* shutting_down,
                   FileNumToPathIdMap* pending_outputs,
                   SequenceNumber newest_snapshot, JobContext* job_context,
                   LogBuffer* log_buffer, Directory* db_directory,
                   CompressionType output_compression, Statistics* stats)
    : dbname_(dbname),
      cfd_(cfd),
      db_options_(db_options),
      mutable_cf_options_(mutable_cf_options),
      env_options_(env_options),
      versions_(versions),
      db_mutex_(db_mutex),
      shutting_down_(shutting_down),
      pending_outputs_(pending_outputs),
      newest_snapshot_(newest_snapshot),
      job_context_(job_context),
      log_buffer_(log_buffer),
      db_directory_(db_directory),
      output_compression_(output_compression),
      stats_(stats) {}

Status FlushJob::Run() {
  // Save the contents of the earliest memtable as a new Table
  uint64_t file_number;
  autovector<MemTable*> mems;
  cfd_->imm()->PickMemtablesToFlush(&mems);
  if (mems.empty()) {
    LogToBuffer(log_buffer_, "[%s] Nothing in memtable to flush",
                cfd_->GetName().c_str());
    return Status::OK();
  }

  // entries mems are (implicitly) sorted in ascending order by their created
  // time. We will use the first memtable's `edit` to keep the meta info for
  // this flush.
  MemTable* m = mems[0];
  VersionEdit* edit = m->GetEdits();
  edit->SetPrevLogNumber(0);
  // SetLogNumber(log_num) indicates logs with number smaller than log_num
  // will no longer be picked up for recovery.
  edit->SetLogNumber(mems.back()->GetNextLogNumber());
  edit->SetColumnFamily(cfd_->GetID());

  // This will release and re-acquire the mutex.
  Status s = WriteLevel0Table(mems, edit, &file_number);

  if (s.ok() &&
      (shutting_down_->load(std::memory_order_acquire) || cfd_->IsDropped())) {
    s = Status::ShutdownInProgress(
        "Database shutdown or Column family drop during flush");
  }

  if (!s.ok()) {
    cfd_->imm()->RollbackMemtableFlush(mems, file_number, pending_outputs_);
  } else {
    // Replace immutable memtable with the generated Table
    s = cfd_->imm()->InstallMemtableFlushResults(
        cfd_, mutable_cf_options_, mems, versions_, db_mutex_, file_number,
        pending_outputs_, &job_context_->memtables_to_free, db_directory_,
        log_buffer_);
  }

  return s;
}

Status FlushJob::WriteLevel0Table(const autovector<MemTable*>& mems,
                                  VersionEdit* edit, uint64_t* filenumber) {
  db_mutex_->AssertHeld();
  const uint64_t start_micros = db_options_.env->NowMicros();
  FileMetaData meta;

  meta.fd = FileDescriptor(versions_->NewFileNumber(), 0, 0);
  *filenumber = meta.fd.GetNumber();
  // path 0 for level 0 file.
  pending_outputs_->insert({meta.fd.GetNumber(), 0});

  const SequenceNumber earliest_seqno_in_memtable =
      mems[0]->GetFirstSequenceNumber();
  Version* base = cfd_->current();
  base->Ref();  // it is likely that we do not need this reference
  Status s;
  {
    db_mutex_->Unlock();
    if (log_buffer_) {
      log_buffer_->FlushBufferToLog();
    }
    std::vector<Iterator*> memtables;
    ReadOptions ro;
    ro.total_order_seek = true;
    Arena arena;
    for (MemTable* m : mems) {
      Log(InfoLogLevel::INFO_LEVEL, db_options_.info_log,
          "[%s] Flushing memtable with next log file: %" PRIu64 "\n",
          cfd_->GetName().c_str(), m->GetNextLogNumber());
      memtables.push_back(m->NewIterator(ro, &arena));
    }
    {
      ScopedArenaIterator iter(NewMergingIterator(&cfd_->internal_comparator(),
                                                  &memtables[0],
                                                  memtables.size(), &arena));
      Log(InfoLogLevel::INFO_LEVEL, db_options_.info_log,
          "[%s] Level-0 flush table #%" PRIu64 ": started",
          cfd_->GetName().c_str(), meta.fd.GetNumber());

      s = BuildTable(dbname_, db_options_.env, *cfd_->ioptions(), env_options_,
                     cfd_->table_cache(), iter.get(), &meta,
                     cfd_->internal_comparator(), newest_snapshot_,
                     earliest_seqno_in_memtable, output_compression_,
                     cfd_->ioptions()->compression_opts, Env::IO_HIGH);
      LogFlush(db_options_.info_log);
    }
    Log(InfoLogLevel::INFO_LEVEL, db_options_.info_log,
        "[%s] Level-0 flush table #%" PRIu64 ": %" PRIu64 " bytes %s",
        cfd_->GetName().c_str(), meta.fd.GetNumber(), meta.fd.GetFileSize(),
        s.ToString().c_str());

    if (!db_options_.disableDataSync && db_directory_ != nullptr) {
      db_directory_->Fsync();
    }
    db_mutex_->Lock();
  }
  base->Unref();

  // re-acquire the most current version
  base = cfd_->current();

  // There could be multiple threads writing to its own level-0 file.
  // The pending_outputs cannot be cleared here, otherwise this newly
  // created file might not be considered as a live-file by another
  // compaction thread that is concurrently deleting obselete files.
  // The pending_outputs can be cleared only after the new version is
  // committed so that other threads can recognize this file as a
  // valid one.
  // pending_outputs_.erase(meta.number);

  // Note that if file_size is zero, the file has been deleted and
  // should not be added to the manifest.
  int level = 0;
  if (s.ok() && meta.fd.GetFileSize() > 0) {
    const Slice min_user_key = meta.smallest.user_key();
    const Slice max_user_key = meta.largest.user_key();
    // if we have more than 1 background thread, then we cannot
    // insert files directly into higher levels because some other
    // threads could be concurrently producing compacted files for
    // that key range.
    if (base != nullptr && db_options_.max_background_compactions <= 1 &&
        db_options_.max_background_flushes == 0 &&
        cfd_->ioptions()->compaction_style == kCompactionStyleLevel) {
      level = base->PickLevelForMemTableOutput(mutable_cf_options_,
                                               min_user_key, max_user_key);
    }
    edit->AddFile(level, meta.fd.GetNumber(), meta.fd.GetPathId(),
                  meta.fd.GetFileSize(), meta.smallest, meta.largest,
                  meta.smallest_seqno, meta.largest_seqno);
  }

  InternalStats::CompactionStats stats(1);
  stats.micros = db_options_.env->NowMicros() - start_micros;
  stats.bytes_written = meta.fd.GetFileSize();
  cfd_->internal_stats()->AddCompactionStats(level, stats);
  cfd_->internal_stats()->AddCFStats(InternalStats::BYTES_FLUSHED,
                                     meta.fd.GetFileSize());
  RecordTick(stats_, COMPACT_WRITE_BYTES, meta.fd.GetFileSize());
  return s;
}

}  // namespace rocksdb
<|endoftext|>


<commit_before>/****************************************************************************
** irexec.c ****************************************************************
****************************************************************************
*
* irexec  - execute programs according to the pressed remote control buttons
*
* Copyright (C) 1998 Trent Piepho <xyzzy@u.washington.edu>
* Copyright (C) 1998 Christoph Bartelmus <lirc@bartelmus.de>
*
*/

#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif

#include <errno.h>
#include <unistd.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#include <sys/types.h>
#include <sys/wait.h>

#include "lirc_client.h"
#include "lirc_log.h"

static const char* const USAGE =
	"Usage: irexec [options] [lircrc config_file]\n"
	"\t-d --daemon\t\tRun in background\n"
	"\t-D --loglevel=level\t'error', 'info', 'notice',... or 0..10\n"
	"\t-n --name=progname\tUse this program name for lircrc matching\n"
	"\t-h --help\t\tDisplay usage summary\n"
	"\t-v --version\t\tDisplay version\n";

static const struct option options[] = {
	{ "help",     no_argument,	 NULL, 'h' },
	{ "version",  no_argument,	 NULL, 'v' },
	{ "daemon",   no_argument,	 NULL, 'd' },
	{ "name",     required_argument, NULL, 'n' },
	{ "loglevel", required_argument, NULL, 'D' },
	{ 0,          0,		 0,    0   }
};

static int opt_daemonize	= 0;
static loglevel_t opt_loglevel	= LIRC_NOLOG;
static const char* opt_progname	= "irexec";

static char path[256] = {0};

/** Run shell command line in isolated process using double fork(). */
static void run_command(const char* cmd)
{
	char* const vp[] = {
		strdupa(SH_PATH), strdupa("-c"), strdupa(cmd), NULL
	};
	pid_t pid1;
	pid_t pid2;

	pid1 = fork();
	if (pid1 < 0) {
		logperror(LIRC_ERROR, "Cannot fork");
		perror("Cannot fork()");
		exit(EXIT_FAILURE);
	}
	if (pid1 == 0) {
		pid2 = fork();
		if (pid2 < 0) {
			logperror(LIRC_ERROR, "Cannot do secondary fork()");
			exit(EXIT_FAILURE);
		}
		if (pid2 == 0) {
			logprintf(LIRC_DEBUG, "Execing command \"%s\"", cmd);
			execvp(SH_PATH, vp);
			/* not reached */
			logperror(LIRC_ERROR, "execvp failed");
			fputs("execvp failed\n", stderr);
		} else {
			waitpid(pid2, NULL, WNOHANG);
			exit(0);
		}
	} else {
		waitpid(pid1, NULL, 0);
	}
}

/** Get buttonclick messages from lircd socket and process them. */
static void process_input(struct lirc_config* config)
{
	char* code;
	char* c;
	int r;

	while (lirc_nextcode(&code) == 0) {
		if (code == NULL)
			continue;
		r = lirc_code2char(config, code, &c);
		while (r == 0 && c != NULL) {
			run_command(c);
			r = lirc_code2char(config, code, &c);
		}
		free(code);
		if (r == -1)
			break;
	}
}

int irexec(const char* configfile)
{
	struct lirc_config* config;

	if (opt_daemonize) {
		if (daemon(0, 0) == -1) {
			perror("Can't daemonize");
			return EXIT_FAILURE;
		}
	}
	if (lirc_readconfig(configfile, &config, NULL) != 0) {
		fputs("Cannot parse config file\n", stderr);
		return EXIT_FAILURE;
	}
	lirc_log_get_clientlog("irexec", path, sizeof(path));
	unlink(path);
	lirc_log_set_file(path);
	lirc_log_open("irexec", 1, opt_loglevel);

	if (lirc_init(opt_progname, opt_daemonize ? 0 : 1) == -1)
		return EXIT_FAILURE;
	process_input(config);
	lirc_deinit();

	lirc_freeconfig(config);
	return EXIT_SUCCESS;
}

int main(int argc, char* argv[])
{
	int c;

	while ((c = getopt_long(argc, argv, "D:hvdn:", options, NULL)) != -1) {
		switch (c) {
		case 'h':
			puts(USAGE);
			return EXIT_SUCCESS;
		case 'v':
			puts("irexec " VERSION);
			return EXIT_SUCCESS;
		case 'd':
			opt_daemonize = 1;
			break;
		case 'n':
			opt_progname = optarg;
			break;
		case 'D':
			opt_loglevel = string2loglevel(optarg);
			break;
		default:
			fputs(USAGE, stderr);
			return EXIT_FAILURE;
		}
	}
	if (optind < argc - 1) {
		fputs("Too many arguments\n", stderr);
		return EXIT_FAILURE;
	}
	if (opt_loglevel == LIRC_BADLEVEL) {
		fprintf(stderr, "Bad debug level: %s\n", optarg);
		return EXIT_FAILURE;
	}
	return irexec(optind != argc ? argv[optind] : NULL);
}
<commit_msg>irexec: Make lirc_init() before readconfig() (#102).<commit_after>/****************************************************************************
** irexec.c ****************************************************************
****************************************************************************
*
* irexec  - execute programs according to the pressed remote control buttons
*
* Copyright (C) 1998 Trent Piepho <xyzzy@u.washington.edu>
* Copyright (C) 1998 Christoph Bartelmus <lirc@bartelmus.de>
*
*/

#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif

#include <errno.h>
#include <unistd.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#include <sys/types.h>
#include <sys/wait.h>

#include "lirc_client.h"
#include "lirc_log.h"

static const char* const USAGE =
	"Usage: irexec [options] [lircrc config_file]\n"
	"\t-d --daemon\t\tRun in background\n"
	"\t-D --loglevel=level\t'error', 'info', 'notice',... or 0..10\n"
	"\t-n --name=progname\tUse this program name for lircrc matching\n"
	"\t-h --help\t\tDisplay usage summary\n"
	"\t-v --version\t\tDisplay version\n";

static const struct option options[] = {
	{ "help",     no_argument,	 NULL, 'h' },
	{ "version",  no_argument,	 NULL, 'v' },
	{ "daemon",   no_argument,	 NULL, 'd' },
	{ "name",     required_argument, NULL, 'n' },
	{ "loglevel", required_argument, NULL, 'D' },
	{ 0,          0,		 0,    0   }
};

static int opt_daemonize	= 0;
static loglevel_t opt_loglevel	= LIRC_NOLOG;
static const char* opt_progname	= "irexec";

static char path[256] = {0};

/** Run shell command line in isolated process using double fork(). */
static void run_command(const char* cmd)
{
	char* const vp[] = {
		strdupa(SH_PATH), strdupa("-c"), strdupa(cmd), NULL
	};
	pid_t pid1;
	pid_t pid2;

	pid1 = fork();
	if (pid1 < 0) {
		logperror(LIRC_ERROR, "Cannot fork");
		perror("Cannot fork()");
		exit(EXIT_FAILURE);
	}
	if (pid1 == 0) {
		pid2 = fork();
		if (pid2 < 0) {
			logperror(LIRC_ERROR, "Cannot do secondary fork()");
			exit(EXIT_FAILURE);
		}
		if (pid2 == 0) {
			logprintf(LIRC_DEBUG, "Execing command \"%s\"", cmd);
			execvp(SH_PATH, vp);
			/* not reached */
			logperror(LIRC_ERROR, "execvp failed");
			fputs("execvp failed\n", stderr);
		} else {
			waitpid(pid2, NULL, WNOHANG);
			exit(0);
		}
	} else {
		waitpid(pid1, NULL, 0);
	}
}

/** Get buttonclick messages from lircd socket and process them. */
static void process_input(struct lirc_config* config)
{
	char* code;
	char* c;
	int r;

	while (lirc_nextcode(&code) == 0) {
		if (code == NULL)
			continue;
		r = lirc_code2char(config, code, &c);
		while (r == 0 && c != NULL) {
			run_command(c);
			r = lirc_code2char(config, code, &c);
		}
		free(code);
		if (r == -1)
			break;
	}
}

int irexec(const char* configfile)
{
	struct lirc_config* config;

	if (opt_daemonize) {
		if (daemon(0, 0) == -1) {
			perror("Can't daemonize");
			return EXIT_FAILURE;
		}
	}
	if (lirc_init(opt_progname, opt_daemonize ? 0 : 1) == -1)
		return EXIT_FAILURE;

	if (lirc_readconfig(configfile, &config, NULL) != 0) {
		fputs("Cannot parse config file\n", stderr);
		return EXIT_FAILURE;
	}
	lirc_log_get_clientlog("irexec", path, sizeof(path));
	unlink(path);
	lirc_log_set_file(path);
	lirc_log_open("irexec", 1, opt_loglevel);

	process_input(config);
	lirc_deinit();

	lirc_freeconfig(config);
	return EXIT_SUCCESS;
}

int main(int argc, char* argv[])
{
	int c;

	while ((c = getopt_long(argc, argv, "D:hvdn:", options, NULL)) != -1) {
		switch (c) {
		case 'h':
			puts(USAGE);
			return EXIT_SUCCESS;
		case 'v':
			puts("irexec " VERSION);
			return EXIT_SUCCESS;
		case 'd':
			opt_daemonize = 1;
			break;
		case 'n':
			opt_progname = optarg;
			break;
		case 'D':
			opt_loglevel = string2loglevel(optarg);
			break;
		default:
			fputs(USAGE, stderr);
			return EXIT_FAILURE;
		}
	}
	if (optind < argc - 1) {
		fputs("Too many arguments\n", stderr);
		return EXIT_FAILURE;
	}
	if (opt_loglevel == LIRC_BADLEVEL) {
		fprintf(stderr, "Bad debug level: %s\n", optarg);
		return EXIT_FAILURE;
	}
	return irexec(optind != argc ? argv[optind] : NULL);
}
<|endoftext|>


<commit_before>/******************************************************************************
 **	Filename:    mf.c
 **	Purpose:     Micro-feature interface to flexible feature extractor.
 **	Author:      Dan Johnson
 **	History:     Thu May 24 09:08:38 1990, DSJ, Created.
 **
 **	(c) Copyright Hewlett-Packard Company, 1988.
 ** 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 Files and Type Defines
----------------------------------------------------------------------------**/
#include "mf.h"

#include "featdefs.h"
#include "mfdefs.h"
#include "mfx.h"

#include <math.h>

/**----------------------------------------------------------------------------
        Global Data Definitions and Declarations
----------------------------------------------------------------------------**/
/**----------------------------------------------------------------------------
              Private Code
----------------------------------------------------------------------------**/
/*---------------------------------------------------------------------------*/
FEATURE_SET ExtractMicros(TBLOB *Blob, const DENORM& denorm) {
/*
 **	Parameters:
 **		Blob		blob to extract micro-features from
 **		denorm  control parameter to feature extractor.
 **	Globals: none
 **	Operation: Call the old micro-feature extractor and then copy
 **		the features into the new format.  Then deallocate the
 **		old micro-features.
 **	Return: Micro-features for Blob.
 **	Exceptions: none
 **	History: Wed May 23 18:06:38 1990, DSJ, Created.
 */
  int NumFeatures;
  MICROFEATURES Features, OldFeatures;
  FEATURE_SET FeatureSet;
  FEATURE Feature;
  MICROFEATURE OldFeature;

  OldFeatures = (MICROFEATURES)BlobMicroFeatures(Blob, denorm);
  if (OldFeatures == NULL)
    return NULL;
  NumFeatures = count (OldFeatures);
  FeatureSet = NewFeatureSet (NumFeatures);

  Features = OldFeatures;
  iterate(Features) {
    OldFeature = (MICROFEATURE) first_node (Features);
    Feature = NewFeature (&MicroFeatureDesc);
    Feature->Params[MFDirection] = OldFeature[ORIENTATION];
    Feature->Params[MFXPosition] = OldFeature[XPOSITION];
    Feature->Params[MFYPosition] = OldFeature[YPOSITION];
    Feature->Params[MFLength] = OldFeature[MFLENGTH];

    // Bulge features are deprecated and should not be used.  Set to 0.
    Feature->Params[MFBulge1] = 0.0f;
    Feature->Params[MFBulge2] = 0.0f;

#ifndef _WIN32
    // Assert that feature parameters are well defined.
    int i;
    for (i = 0; i < Feature->Type->NumParams; i++) {
      assert (!isnan(Feature->Params[i]));
    }
#endif

    AddFeature(FeatureSet, Feature);
  }
  FreeMicroFeatures(OldFeatures);
  return (FeatureSet);

}                                /* ExtractMicros */
<commit_msg>Fixed build break<commit_after>/******************************************************************************
 **	Filename:    mf.c
 **	Purpose:     Micro-feature interface to flexible feature extractor.
 **	Author:      Dan Johnson
 **	History:     Thu May 24 09:08:38 1990, DSJ, Created.
 **
 **	(c) Copyright Hewlett-Packard Company, 1988.
 ** 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 Files and Type Defines
----------------------------------------------------------------------------**/
#include "mf.h"

#include "featdefs.h"
#include "mfdefs.h"
#include "mfx.h"

#include <math.h>

/**----------------------------------------------------------------------------
        Global Data Definitions and Declarations
----------------------------------------------------------------------------**/
/**----------------------------------------------------------------------------
              Private Code
----------------------------------------------------------------------------**/
/*---------------------------------------------------------------------------*/
FEATURE_SET ExtractMicros(TBLOB *Blob, const DENORM& denorm) {
/*
 **	Parameters:
 **		Blob		blob to extract micro-features from
 **		denorm  control parameter to feature extractor.
 **	Globals: none
 **	Operation: Call the old micro-feature extractor and then copy
 **		the features into the new format.  Then deallocate the
 **		old micro-features.
 **	Return: Micro-features for Blob.
 **	Exceptions: none
 **	History: Wed May 23 18:06:38 1990, DSJ, Created.
 */
  int NumFeatures;
  MICROFEATURES Features, OldFeatures;
  FEATURE_SET FeatureSet;
  FEATURE Feature;
  MICROFEATURE OldFeature;

  OldFeatures = (MICROFEATURES)BlobMicroFeatures(Blob, denorm);
  if (OldFeatures == NULL)
    return NULL;
  NumFeatures = count (OldFeatures);
  FeatureSet = NewFeatureSet (NumFeatures);

  Features = OldFeatures;
  iterate(Features) {
    OldFeature = (MICROFEATURE) first_node (Features);
    Feature = NewFeature (&MicroFeatureDesc);
    Feature->Params[MFDirection] = OldFeature[ORIENTATION];
    Feature->Params[MFXPosition] = OldFeature[XPOSITION];
    Feature->Params[MFYPosition] = OldFeature[YPOSITION];
    Feature->Params[MFLength] = OldFeature[MFLENGTH];

    // Bulge features are deprecated and should not be used.  Set to 0.
    Feature->Params[MFBulge1] = 0.0f;
    Feature->Params[MFBulge2] = 0.0f;

#ifndef _WIN32
    // Assert that feature parameters are well defined.
    int i;
    for (i = 0; i < Feature->Type->NumParams; i++) {
      ASSERT_HOST(!isnan(Feature->Params[i]));
    }
#endif

    AddFeature(FeatureSet, Feature);
  }
  FreeMicroFeatures(OldFeatures);
  return FeatureSet;
}                                /* ExtractMicros */
<|endoftext|>


<commit_before>/* filter_streams_py.cc
   Wolfgang Sourdeau
   Jeremy Barnes, Dec 8th 2015
   Copyright (c) 2015  Datacratic.  All rights reserved.

   Python wrappers for ML::filter_[oi]stream
*/

#include <Python.h>
#include <string>
#include "platform/python/pointer_fix.h" //must come before boost python
#include <boost/python.hpp>
#include "filter_streams.h"

using namespace std;
using namespace boost;

namespace {

void filter_ostream__write(ML::filter_ostream & stream,
                           const string & data)
{
    stream.write(data.c_str(), data.size());
}

std::string filter_istream__read0(ML::filter_istream & stream)
{
    return stream.readAll();
}

std::string filter_istream__read1(ML::filter_istream & stream, size_t nBytes)
{
    string result;

    char buffer[65536];
    size_t remaining = nBytes;
    while (stream && remaining > 0) {
        size_t toRead = sizeof(buffer);
        if (remaining < toRead) {
            toRead = remaining;
        }
        stream.read(buffer, toRead);
        size_t readSize = stream.gcount();
        result.append(buffer, readSize);
        remaining -= readSize;
    }

    return result;
}

} // file scope

BOOST_PYTHON_MODULE(filter_streams) {
    // BOOST_PYTHON_MODULE_INIT();

    python::class_<ML::filter_ostream,
                   std::shared_ptr<ML::filter_ostream>,
                   boost::noncopyable>
        ("filter_ostream", python::init<const std::string &>())
         .def("write", &filter_ostream__write)
         .def("close", &ML::filter_ostream::close);

    python::class_<ML::filter_istream,
                   std::shared_ptr<ML::filter_istream>,
                   boost::noncopyable>
        ("filter_istream", python::init<const std::string &>())
         .def("read", &filter_istream__read0)
         .def("read", &filter_istream__read1)
         .def("close", &ML::filter_istream::close);
}
<commit_msg>RTBOPT-1365: added "readline"<commit_after>/* filter_streams_py.cc
   Wolfgang Sourdeau
   Jeremy Barnes, Dec 8th 2015
   Copyright (c) 2015  Datacratic.  All rights reserved.

   Python wrappers for ML::filter_[oi]stream
*/

#include <Python.h>
#include <string>
#include "platform/python/pointer_fix.h" //must come before boost python
#include <boost/python.hpp>
#include "filter_streams.h"

using namespace std;
using namespace boost;

namespace {

void filter_ostream__write(ML::filter_ostream & stream,
                           const string & data)
{
    stream.write(data.c_str(), data.size());
}

std::string filter_istream__read0(ML::filter_istream & stream)
{
    return stream.readAll();
}

std::string filter_istream__read1(ML::filter_istream & stream, size_t nBytes)
{
    string result;

    char buffer[65536];
    size_t remaining = nBytes;
    while (stream && remaining > 0) {
        size_t toRead = sizeof(buffer);
        if (remaining < toRead) {
            toRead = remaining;
        }
        stream.read(buffer, toRead);
        size_t readSize = stream.gcount();
        result.append(buffer, readSize);
        remaining -= readSize;
    }

    return result;
}

std::string filter_istream__readline1(ML::filter_istream & stream,
                                      ssize_t nBytes)
{
    string line;

    if (stream) {
        getline(stream, line);
        line += "\n";
        if (nBytes > -1) {
            line.resize(nBytes);
        }
    }

    return line;
}

std::string filter_istream__readline0(ML::filter_istream & stream)
{
    return filter_istream__readline1(stream, -1);
}

} // file scope

BOOST_PYTHON_MODULE(filter_streams) {
    // BOOST_PYTHON_MODULE_INIT();

    python::class_<ML::filter_ostream,
                   std::shared_ptr<ML::filter_ostream>,
                   boost::noncopyable>
        ("filter_ostream", python::init<const std::string &>())
         .def("write", &filter_ostream__write)
         .def("close", &ML::filter_ostream::close);

    python::class_<ML::filter_istream,
                   std::shared_ptr<ML::filter_istream>,
                   boost::noncopyable>
        ("filter_istream", python::init<const std::string &>())
         .def("read", &filter_istream__read0)
         .def("read", &filter_istream__read1)
         .def("readline", &filter_istream__readline0)
         .def("readline", &filter_istream__readline1)
         .def("close", &ML::filter_istream::close);
}
<|endoftext|>


<commit_before>// Copyright (c) 2016 Kasper Kronborg Isager and Radosław Niemczyk.
#include <vector>
#include <iostream>
#include <fstream>
#include <hayai/hayai.hpp>
#include <hayai/hayai_posix_main.cpp>
#include <hemingway/vector.hpp>
#include <hemingway/table.hpp>

using namespace lsh;

std::vector<vector> parse(std::string path) {
  std::ifstream stream(path, std::ios::binary);
  std::vector<vector> vectors;

  std::vector<char> buffer(1 << 20);

  while (!stream.eof()) {
    stream.read(&buffer[0], 1 << 20);

    int read = stream.gcount();

    for (int i = 0; i < read; i += 8) {
      unsigned long n;

      for (int j = 0; j < 8; j++) {
        ((char*) &n)[j] = buffer[i + j];
      }

      std::vector<bool> c(64);

      for (int j = 0; j < 64; j++) {
          c[j] = (n >> (63 - j)) & 1;
      }

      vectors.push_back(vector(c));
    }
  }

  return vectors;
}

std::vector<vector> vs = parse("bench/data/vectors.bin");
std::vector<vector> qs = parse("bench/data/queries.bin");

std::vector<vector> gt;

table t_lin(table::brute({.dimensions = 64}));

table t_cla({.dimensions = 64, .samples = 31, .partitions = 31});
table t_cov({.dimensions = 64, .radius = 4});

unsigned int vn = vs.size();
unsigned int qn = qs.size();

unsigned int vi;
unsigned int qi;

unsigned int runs = 50;

BENCHMARK(table, insert_linear, runs, vn / runs) {
  t_lin.insert(vs[vi++ % vn]);
}

BENCHMARK(table, insert_classic, runs, vn / runs) {
  t_cla.insert(vs[vi++ % vn]);
}

BENCHMARK(table, insert_covering, runs, vn / runs) {
  t_cov.insert(vs[vi++ % vn]);
}

BENCHMARK(table, query_linear, runs, qn / runs) {
  vector q = qs[qi++ % qn];
  vector r = t_lin.query(q);

  gt.push_back(r);
}

BENCHMARK(table, query_classic, runs, qn / runs) {
  unsigned int i = qi++ % qn;

  vector q = qs[i];
  vector t = gt[i];

  vector r = t_cla.query(q);

  if (vector::distance(q, t) <= 4) {
    if (r.size() == 0) {
    }

    else if (vector::distance(q, r) > 4) {
    }
  }
}

BENCHMARK(table, query_covering, runs, qn / runs) {
  unsigned int i = qi++ % qn;

  vector q = qs[i];
  vector t = gt[i];

  vector r = t_cov.query(q);

  if (vector::distance(q, t) <= 4) {
    if (r.size() == 0) {
    }

    else if (vector::distance(q, r) > 4) {
    }
  }
}
<commit_msg>Print information about false negatives<commit_after>// Copyright (c) 2016 Kasper Kronborg Isager and Radosław Niemczyk.
#include <vector>
#include <iostream>
#include <fstream>
#include <hayai/hayai.hpp>
#include <hayai/hayai_posix_main.cpp>
#include <hemingway/vector.hpp>
#include <hemingway/table.hpp>

using namespace lsh;

std::vector<vector> parse(std::string path) {
  std::ifstream stream(path, std::ios::binary);
  std::vector<vector> vectors;

  std::vector<char> buffer(1 << 20);

  while (!stream.eof()) {
    stream.read(&buffer[0], 1 << 20);

    int read = stream.gcount();

    for (int i = 0; i < read; i += 8) {
      unsigned long n;

      for (int j = 0; j < 8; j++) {
        ((char*) &n)[j] = buffer[i + j];
      }

      std::vector<bool> c(64);

      for (int j = 0; j < 64; j++) {
          c[j] = (n >> (63 - j)) & 1;
      }

      vectors.push_back(vector(c));
    }
  }

  return vectors;
}

std::vector<vector> vs = parse("bench/data/vectors.bin");
std::vector<vector> qs = parse("bench/data/queries.bin");

std::vector<vector> gt;

table t_lin(table::brute({.dimensions = 64}));

table t_cla({.dimensions = 64, .samples = 31, .partitions = 31});
table t_cov({.dimensions = 64, .radius = 4});

unsigned int vn = vs.size();
unsigned int qn = qs.size();

unsigned int vi;
unsigned int qi;

unsigned int runs = 50;

BENCHMARK(table, insert_linear, runs, vn / runs) {
  t_lin.insert(vs[vi++ % vn]);
}

BENCHMARK(table, insert_classic, runs, vn / runs) {
  t_cla.insert(vs[vi++ % vn]);
}

BENCHMARK(table, insert_covering, runs, vn / runs) {
  t_cov.insert(vs[vi++ % vn]);
}

BENCHMARK(table, query_linear, runs, qn / runs) {
  vector q = qs[qi++ % qn];
  vector r = t_lin.query(q);

  gt.push_back(r);
}

BENCHMARK(table, query_classic, runs, qn / runs) {
  unsigned int i = qi++ % qn;

  vector q = qs[i];
  vector t = gt[i];

  vector r = t_cla.query(q);

  if (vector::distance(q, t) <= 4) {
    if (r.size() == 0) {
      std::cout << "                ";
      std::cout << "Incorrect result: Found nothing" << std::endl;
    }

    else if (vector::distance(q, r) > 4) {
      std::cout << "                ";
      std::cout << "Incorrect result: False negative" << std::endl;
    }
  }
}

BENCHMARK(table, query_covering, runs, qn / runs) {
  unsigned int i = qi++ % qn;

  vector q = qs[i];
  vector t = gt[i];

  vector r = t_cov.query(q);

  if (vector::distance(q, t) <= 4) {
    if (r.size() == 0) {
      std::cout << "                ";
      std::cout << "Incorrect result: Found nothing" << std::endl;
    }

    else if (vector::distance(q, r) > 4) {
      std::cout << "                ";
      std::cout << "Incorrect result: False negative" << std::endl;
    }
  }
}
<|endoftext|>


<commit_before>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2011 Ulrich von Zadow
//
//  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 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Current versions can be found at www.libavg.de
//

#include "FFMpegDemuxer.h"

#include "../base/ScopeTimer.h"
#include "../base/ObjectCounter.h"
#include "../base/Exception.h"

#include <cstring>
#include <iostream>

using namespace std;

namespace avg {

FFMpegDemuxer::FFMpegDemuxer(AVFormatContext * pFormatContext, vector<int> streamIndexes)
    : m_pFormatContext(pFormatContext)
{
    ObjectCounter::get()->incRef(&typeid(*this));
    for (unsigned i = 0; i < streamIndexes.size(); ++i) {
        m_PacketLists[streamIndexes[i]] = PacketList();
    }
}

FFMpegDemuxer::~FFMpegDemuxer()
{
    clearPacketCache();
    ObjectCounter::get()->decRef(&typeid(*this));
}

AVPacket * FFMpegDemuxer::getPacket(int streamIndex)
{
    // Make sure enableStream was called on streamIndex.
    AVG_ASSERT(m_PacketLists.size() > 0);
    AVG_ASSERT(streamIndex > -1 && streamIndex < 10);

    if (m_PacketLists.find(streamIndex) == m_PacketLists.end()) {
        cerr << this << ": getPacket: Stream " << streamIndex << " not found." << endl;
        dump();
        AVG_ASSERT(false);
    }

    PacketList& curPacketList = m_PacketLists.find(streamIndex)->second;
    AVPacket* pPacket;
    if (!curPacketList.empty()) {
        // The stream has packets queued already.
        pPacket = curPacketList.front();
        curPacketList.pop_front();
    } else {
        // No packets queued for this stream -> read and queue packets until we get one
        // that is meant for this stream.
        do {
            pPacket = new AVPacket;
            memset(pPacket, 0, sizeof(AVPacket));
            int err = av_read_frame(m_pFormatContext, pPacket);
            if (err < 0) {
                // EOF
                av_free_packet(pPacket);
                delete pPacket;
                pPacket = 0;
                return 0;
            }
            if (pPacket->stream_index != streamIndex) {
                if (m_PacketLists.find(pPacket->stream_index) != m_PacketLists.end()) {
                    // Relevant stream, but not ours
                    av_dup_packet(pPacket);
                    PacketList& otherPacketList =
                            m_PacketLists.find(pPacket->stream_index)->second;
                    otherPacketList.push_back(pPacket);
                } else {
                    // Disabled stream
                    av_free_packet(pPacket);
                    delete pPacket;
                    pPacket = 0;
                }
            } else {
                // Our stream
                av_dup_packet(pPacket);
            }
        } while (!pPacket || pPacket->stream_index != streamIndex);
    }

    return pPacket;
}

void FFMpegDemuxer::seek(float destTime)
{
#if LIBAVFORMAT_BUILD <= 4616
    av_seek_frame(m_pFormatContext, -1, destTime*1000000);
#else
#if LIBAVFORMAT_BUILD < ((49<<16)+(0<<8)+0)
    av_seek_frame(m_pFormatContext, -1, destTime*1000000, 0);
#else
    int err = av_seek_frame(m_pFormatContext, -1, (long long)(destTime*AV_TIME_BASE),
            AVSEEK_FLAG_BACKWARD);
    if (err < 0) {
        // Needed for some strange videos. See bug #436.
        err = av_seek_frame(m_pFormatContext, -1, (long long)(destTime*AV_TIME_BASE),
                AVSEEK_FLAG_ANY);
        AVG_ASSERT(err >= 0);
   }
   AVG_ASSERT(err >= 0);
#endif
#endif
    clearPacketCache();
}

void FFMpegDemuxer::clearPacketCache()
{
    map<int, PacketList>::iterator it;
    for (it = m_PacketLists.begin(); it != m_PacketLists.end(); ++it) {
        PacketList::iterator it2;
        PacketList* pPacketList = &(it->second);
        for (it2 = pPacketList->begin(); it2 != pPacketList->end(); ++it2) {
            av_free_packet(*it2);
            delete *it2;
        }
        pPacketList->clear();
    }
}

void FFMpegDemuxer::dump()
{
    map<int, PacketList>::iterator it;
    cerr << "FFMpegDemuxer " << this << endl;
    cerr << "packetlists.size(): " << int(m_PacketLists.size()) << endl;
    for (it = m_PacketLists.begin(); it != m_PacketLists.end(); ++it) {
        cerr << "  " << it->first << ":  " << int(it->second.size()) << endl;
    }
}

}
<commit_msg>Reverted last bogus commit.<commit_after>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2011 Ulrich von Zadow
//
//  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 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Current versions can be found at www.libavg.de
//

#include "FFMpegDemuxer.h"

#include "../base/ScopeTimer.h"
#include "../base/ObjectCounter.h"
#include "../base/Exception.h"

#include <cstring>
#include <iostream>

using namespace std;

namespace avg {

FFMpegDemuxer::FFMpegDemuxer(AVFormatContext * pFormatContext, vector<int> streamIndexes)
    : m_pFormatContext(pFormatContext)
{
    ObjectCounter::get()->incRef(&typeid(*this));
    for (unsigned i = 0; i < streamIndexes.size(); ++i) {
        m_PacketLists[streamIndexes[i]] = PacketList();
    }
}

FFMpegDemuxer::~FFMpegDemuxer()
{
    clearPacketCache();
    ObjectCounter::get()->decRef(&typeid(*this));
}

AVPacket * FFMpegDemuxer::getPacket(int streamIndex)
{
    // Make sure enableStream was called on streamIndex.
    AVG_ASSERT(m_PacketLists.size() > 0);
    AVG_ASSERT(streamIndex > -1 && streamIndex < 10);

    if (m_PacketLists.find(streamIndex) == m_PacketLists.end()) {
        cerr << this << ": getPacket: Stream " << streamIndex << " not found." << endl;
        dump();
        AVG_ASSERT(false);
    }

    PacketList& curPacketList = m_PacketLists.find(streamIndex)->second;
    AVPacket* pPacket;
    if (!curPacketList.empty()) {
        // The stream has packets queued already.
        pPacket = curPacketList.front();
        curPacketList.pop_front();
    } else {
        // No packets queued for this stream -> read and queue packets until we get one
        // that is meant for this stream.
        do {
            pPacket = new AVPacket;
            memset(pPacket, 0, sizeof(AVPacket));
            int err = av_read_frame(m_pFormatContext, pPacket);
            if (err < 0) {
                // EOF
                av_free_packet(pPacket);
                delete pPacket;
                pPacket = 0;
                return 0;
            }
            if (pPacket->stream_index != streamIndex) {
                if (m_PacketLists.find(pPacket->stream_index) != m_PacketLists.end()) {
                    // Relevant stream, but not ours
                    av_dup_packet(pPacket);
                    PacketList& otherPacketList =
                            m_PacketLists.find(pPacket->stream_index)->second;
                    otherPacketList.push_back(pPacket);
                } else {
                    // Disabled stream
                    av_free_packet(pPacket);
                    delete pPacket;
                    pPacket = 0;
                }
            } else {
                // Our stream
                av_dup_packet(pPacket);
            }
        } while (!pPacket || pPacket->stream_index != streamIndex);
    }

    return pPacket;
}

void FFMpegDemuxer::seek(float destTime)
{
#if LIBAVFORMAT_BUILD <= 4616
    av_seek_frame(m_pFormatContext, -1, destTime*1000000);
#else
#if LIBAVFORMAT_BUILD < ((49<<16)+(0<<8)+0)
    av_seek_frame(m_pFormatContext, -1, destTime*1000000, 0);
#else
   av_seek_frame(m_pFormatContext, -1, (long long)(destTime*AV_TIME_BASE),
            AVSEEK_FLAG_BACKWARD);
#endif
#endif
    clearPacketCache();
}

void FFMpegDemuxer::clearPacketCache()
{
    map<int, PacketList>::iterator it;
    for (it = m_PacketLists.begin(); it != m_PacketLists.end(); ++it) {
        PacketList::iterator it2;
        PacketList* pPacketList = &(it->second);
        for (it2 = pPacketList->begin(); it2 != pPacketList->end(); ++it2) {
            av_free_packet(*it2);
            delete *it2;
        }
        pPacketList->clear();
    }
}

void FFMpegDemuxer::dump()
{
    map<int, PacketList>::iterator it;
    cerr << "FFMpegDemuxer " << this << endl;
    cerr << "packetlists.size(): " << int(m_PacketLists.size()) << endl;
    for (it = m_PacketLists.begin(); it != m_PacketLists.end(); ++it) {
        cerr << "  " << it->first << ":  " << int(it->second.size()) << endl;
    }
}

}
<|endoftext|>


<commit_before>#include "../stdafx.h"

#include "wrapper/pki/cert_request_info.h"
#include "wrapper/pki/key.h"

void CertificationRequestInfo::setSubject(Handle<std::string> xName) {
	LOGGER_FN();

	try{
		if (xName.isEmpty()){
			THROW_EXCEPTION(0, CertificationRequestInfo, NULL, "Parameter 1 can not be NULL");
		}

		LOGGER_OPENSSL(X509_NAME_new);
		X509_NAME *name = X509_NAME_new();

		std::string strName = xName->c_str();
		strName = strName + "/";

		std::string sl = "/";
		std::string eq = "=";

		size_t pos = 0, posInBuf = 0;

		std::string buf, field, param;

		while ((pos = strName.find(sl)) != std::string::npos)  {
			buf = strName.substr(0, pos);
			if (buf.length() > 0){
				posInBuf = buf.find(eq);
				field = buf.substr(0, posInBuf);
				param = buf.substr(posInBuf + 1, buf.length());

				LOGGER_OPENSSL(X509_NAME_add_entry_by_txt);
				if (!X509_NAME_add_entry_by_txt(name, field.c_str(), MBSTRING_ASC, (const unsigned char *)param.c_str(), -1, -1, 0)){
					THROW_OPENSSL_EXCEPTION(0, CertificationRequestInfo, NULL, "X509_NAME_add_entry_by_txt 'Unable add param to X509_NAME'");
				}
			}
			strName.erase(0, pos + sl.length());
		}

		LOGGER_OPENSSL(X509_NAME_dup);
		this->internal()->subject = X509_NAME_dup(name);
		if (name){
			LOGGER_OPENSSL(X509_NAME_free);
			X509_NAME_free(name);
		}
	}
	catch (Handle<Exception> e){
		THROW_EXCEPTION(0, CertificationRequestInfo, e, "Error set subject to X509_REQ_info");
	}
}

void CertificationRequestInfo::setSubjectPublicKey(Handle<Key> key){
	LOGGER_FN();

	if (key.isEmpty()){
		THROW_EXCEPTION(0, CertificationRequestInfo, NULL, "Error set subject to X509_REQ_info");
	}

	LOGGER_OPENSSL(X509_PUBKEY_set);
	if (!X509_PUBKEY_set(&(this->internal()->pubkey), key->internal())){
		THROW_OPENSSL_EXCEPTION(0, CertificationRequestInfo, NULL, "X509_PUBKEY_set");
	}
}

void CertificationRequestInfo::setVersion(long version){
	LOGGER_FN();

	if (this->internal() == NULL){
		THROW_EXCEPTION(0, CertificationRequestInfo, NULL, "X509_REQ_info cannot be NULL");
	}

	LOGGER_OPENSSL(ASN1_INTEGER_set);
	if(!ASN1_INTEGER_set(this->internal()->version, version)){
		THROW_EXCEPTION(0, CertificationRequestInfo, NULL, "Error set version to X509_REQ_info");
	}
}

Handle<std::string> CertificationRequestInfo::getSubject() {
	LOGGER_FN();

	LOGGER_OPENSSL(X509_REQ_get_subject_name);
	X509_NAME *name = this->internal()->subject;
	if (!name)
		THROW_EXCEPTION(0, CertificationRequestInfo, NULL, "X509_REQ_INFO subject is NULL");

	LOGGER_OPENSSL(X509_NAME_oneline_ex);
	std::string str_name = X509_NAME_oneline_ex(name);

	Handle<std::string> res = new std::string(str_name.c_str(), str_name.length());

	return res;
}

long CertificationRequestInfo::getVersion() {
	LOGGER_FN();

	ASN1_INTEGER *ver = this->internal()->version;

	if (!ver) {
		THROW_EXCEPTION(0, CertificationRequestInfo, NULL, "X509_REQ_INFO version is NULL");
	}

	LOGGER_OPENSSL(ASN1_INTEGER_get);
	long res = ASN1_INTEGER_get(this->internal()->version);

	return res;
}

Handle<Key> CertificationRequestInfo::getPublicKey() {
	LOGGER_FN();

	Handle<Key> key = NULL;

	X509_REQ_INFO *xx = this->internal();

	if (this->internal()->pubkey) {
		LOGGER_OPENSSL(X509_PUBKEY_get);
		key = new Key(X509_PUBKEY_get(this->internal()->pubkey));
	}
	else {
		THROW_EXCEPTION(0, CertificationRequestInfo, NULL, "X509_REQ_INFO pubkey is NULL");
	}

	return key;
}
<commit_msg>del unused code<commit_after>#include "../stdafx.h"

#include "wrapper/pki/cert_request_info.h"
#include "wrapper/pki/key.h"

void CertificationRequestInfo::setSubject(Handle<std::string> xName) {
	LOGGER_FN();

	try{
		if (xName.isEmpty()){
			THROW_EXCEPTION(0, CertificationRequestInfo, NULL, "Parameter 1 can not be NULL");
		}

		LOGGER_OPENSSL(X509_NAME_new);
		X509_NAME *name = X509_NAME_new();

		std::string strName = xName->c_str();
		strName = strName + "/";

		std::string sl = "/";
		std::string eq = "=";

		size_t pos = 0, posInBuf = 0;

		std::string buf, field, param;

		while ((pos = strName.find(sl)) != std::string::npos)  {
			buf = strName.substr(0, pos);
			if (buf.length() > 0){
				posInBuf = buf.find(eq);
				field = buf.substr(0, posInBuf);
				param = buf.substr(posInBuf + 1, buf.length());

				LOGGER_OPENSSL(X509_NAME_add_entry_by_txt);
				if (!X509_NAME_add_entry_by_txt(name, field.c_str(), MBSTRING_ASC, (const unsigned char *)param.c_str(), -1, -1, 0)){
					THROW_OPENSSL_EXCEPTION(0, CertificationRequestInfo, NULL, "X509_NAME_add_entry_by_txt 'Unable add param to X509_NAME'");
				}
			}
			strName.erase(0, pos + sl.length());
		}

		LOGGER_OPENSSL(X509_NAME_dup);
		this->internal()->subject = X509_NAME_dup(name);
		if (name){
			LOGGER_OPENSSL(X509_NAME_free);
			X509_NAME_free(name);
		}
	}
	catch (Handle<Exception> e){
		THROW_EXCEPTION(0, CertificationRequestInfo, e, "Error set subject to X509_REQ_info");
	}
}

void CertificationRequestInfo::setSubjectPublicKey(Handle<Key> key){
	LOGGER_FN();

	if (key.isEmpty()){
		THROW_EXCEPTION(0, CertificationRequestInfo, NULL, "Error set subject to X509_REQ_info");
	}

	LOGGER_OPENSSL(X509_PUBKEY_set);
	if (!X509_PUBKEY_set(&(this->internal()->pubkey), key->internal())){
		THROW_OPENSSL_EXCEPTION(0, CertificationRequestInfo, NULL, "X509_PUBKEY_set");
	}
}

void CertificationRequestInfo::setVersion(long version){
	LOGGER_FN();

	if (this->internal() == NULL){
		THROW_EXCEPTION(0, CertificationRequestInfo, NULL, "X509_REQ_info cannot be NULL");
	}

	LOGGER_OPENSSL(ASN1_INTEGER_set);
	if(!ASN1_INTEGER_set(this->internal()->version, version)){
		THROW_EXCEPTION(0, CertificationRequestInfo, NULL, "Error set version to X509_REQ_info");
	}
}

Handle<std::string> CertificationRequestInfo::getSubject() {
	LOGGER_FN();

	LOGGER_OPENSSL(X509_REQ_get_subject_name);
	X509_NAME *name = this->internal()->subject;
	if (!name)
		THROW_EXCEPTION(0, CertificationRequestInfo, NULL, "X509_REQ_INFO subject is NULL");

	LOGGER_OPENSSL(X509_NAME_oneline_ex);
	std::string str_name = X509_NAME_oneline_ex(name);

	Handle<std::string> res = new std::string(str_name.c_str(), str_name.length());

	return res;
}

long CertificationRequestInfo::getVersion() {
	LOGGER_FN();

	ASN1_INTEGER *ver = this->internal()->version;

	if (!ver) {
		THROW_EXCEPTION(0, CertificationRequestInfo, NULL, "X509_REQ_INFO version is NULL");
	}

	LOGGER_OPENSSL(ASN1_INTEGER_get);
	long res = ASN1_INTEGER_get(this->internal()->version);

	return res;
}

Handle<Key> CertificationRequestInfo::getPublicKey() {
	LOGGER_FN();

	Handle<Key> key = NULL;

	if (this->internal()->pubkey) {
		LOGGER_OPENSSL(X509_PUBKEY_get);
		key = new Key(X509_PUBKEY_get(this->internal()->pubkey));
	}
	else {
		THROW_EXCEPTION(0, CertificationRequestInfo, NULL, "X509_REQ_INFO pubkey is NULL");
	}

	return key;
}
<|endoftext|>