text:
/*
 *  Android audio device implementation (JNI/AudioTrack usage)
 */

// TODO(xians): Break out attach and detach current thread to JVM to
// separate functions.

#include "webrtc/modules/audio_device/android/audio_track_jni.h"

#include <android/log.h>
#include <assert.h>
#include <stdlib.h>

#include "webrtc/modules/audio_device/audio_device_config.h"
#include "webrtc/modules/audio_device/audio_device_utility.h"

#include "webrtc/system_wrappers/interface/event_wrapper.h"
#include "webrtc/system_wrappers/interface/thread_wrapper.h"
#include "webrtc/system_wrappers/interface/trace.h"

namespace webrtc {

JavaVM* AudioTrackJni::globalJvm = NULL;
JNIEnv* AudioTrackJni::globalJNIEnv = NULL;
jobject AudioTrackJni::globalContext = NULL;
jclass AudioTrackJni::globalScClass = NULL;

int32_t AudioTrackJni::SetAndroidAudioDeviceObjects(void* javaVM, void* env,
                                                    void* context) {
  assert(env);
  globalJvm = reinterpret_cast<JavaVM*>(javaVM);
  globalJNIEnv = reinterpret_cast<JNIEnv*>(env);
  // Get java class type (note path to class packet).
  jclass javaScClassLocal = globalJNIEnv->FindClass(
      "com/livecom/webrtc/voiceengine/WebRtcAudioTrack");

  if (!javaScClassLocal) {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, -1,
                 "%s: could not find java class", __FUNCTION__);
    return -1; // exception thrown
  }

  // Create a global reference to the class (to tell JNI that we are
  // referencing it after this function has returned).
  globalScClass = reinterpret_cast<jclass> (
      globalJNIEnv->NewGlobalRef(javaScClassLocal));
  if (!globalScClass) {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, -1,
                 "%s: could not create reference", __FUNCTION__);
    return -1;
  }

  globalContext = globalJNIEnv->NewGlobalRef(
      reinterpret_cast<jobject>(context));
  if (!globalContext) {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, -1,
                 "%s: could not create context reference", __FUNCTION__);
    return -1;
  }

  // Delete local class ref, we only use the global ref
  globalJNIEnv->DeleteLocalRef(javaScClassLocal);
  return 0;
}

void AudioTrackJni::ClearAndroidAudioDeviceObjects() {
  WEBRTC_TRACE(kTraceStateInfo, kTraceAudioDevice, -1,
               "%s: env is NULL, assuming deinit", __FUNCTION__);

  globalJvm = NULL;
  if (!globalJNIEnv) {
    WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, -1,
                 "%s: saved env already NULL", __FUNCTION__);
    return;
  }

  globalJNIEnv->DeleteGlobalRef(globalContext);
  globalContext = reinterpret_cast<jobject>(NULL);

  globalJNIEnv->DeleteGlobalRef(globalScClass);
  globalScClass = reinterpret_cast<jclass>(NULL);

  globalJNIEnv = reinterpret_cast<JNIEnv*>(NULL);
}

AudioTrackJni::AudioTrackJni(const int32_t id)
    : _javaVM(NULL),
      _jniEnvPlay(NULL),
      _javaScClass(0),
      _javaScObj(0),
      _javaPlayBuffer(0),
      _javaDirectPlayBuffer(NULL),
      _javaMidPlayAudio(0),
      _ptrAudioBuffer(NULL),
      _critSect(*CriticalSectionWrapper::CreateCriticalSection()),
      _id(id),
      _initialized(false),
      _timeEventPlay(*EventWrapper::Create()),
      _playStartStopEvent(*EventWrapper::Create()),
      _ptrThreadPlay(NULL),
      _playThreadID(0),
      _playThreadIsInitialized(false),
      _shutdownPlayThread(false),
      _playoutDeviceIsSpecified(false),
      _playing(false),
      _playIsInitialized(false),
      _speakerIsInitialized(false),
      _startPlay(false),
      _playWarning(0),
      _playError(0),
      _delayPlayout(0),
      _samplingFreqOut((N_PLAY_SAMPLES_PER_SEC/1000)),
      _maxSpeakerVolume(0) {
}

AudioTrackJni::~AudioTrackJni() {
  WEBRTC_TRACE(kTraceMemory, kTraceAudioDevice, _id,
               "%s destroyed", __FUNCTION__);

  Terminate();

  delete &_playStartStopEvent;
  delete &_timeEventPlay;
  delete &_critSect;
}

int32_t AudioTrackJni::Init() {
  CriticalSectionScoped lock(&_critSect);
  if (_initialized)
  {
    return 0;
  }

  _playWarning = 0;
  _playError = 0;

  // Init Java member variables
  // and set up JNI interface to
  // AudioDeviceAndroid java class
  if (InitJavaResources() != 0)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "%s: Failed to init Java resources", __FUNCTION__);
    return -1;
  }

  // Check the sample rate to be used for playback and recording
  // and the max playout volume
  if (InitSampleRate() != 0)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "%s: Failed to init samplerate", __FUNCTION__);
    return -1;
  }

  const char* threadName = "jni_audio_render_thread";
  _ptrThreadPlay = ThreadWrapper::CreateThread(PlayThreadFunc, this,
                                               kRealtimePriority, threadName);
  if (_ptrThreadPlay == NULL)
  {
    WEBRTC_TRACE(kTraceCritical, kTraceAudioDevice, _id,
                 "  failed to create the play audio thread");
    return -1;
  }

  unsigned int threadID = 0;
  if (!_ptrThreadPlay->Start(threadID))
  {
    WEBRTC_TRACE(kTraceCritical, kTraceAudioDevice, _id,
                 "  failed to start the play audio thread");
    delete _ptrThreadPlay;
    _ptrThreadPlay = NULL;
    return -1;
  }
  _playThreadID = threadID;

  _initialized = true;

  return 0;
}

int32_t AudioTrackJni::Terminate() {
  CriticalSectionScoped lock(&_critSect);
  if (!_initialized)
  {
    return 0;
  }

  StopPlayout();
  _shutdownPlayThread = true;
  _timeEventPlay.Set(); // Release rec thread from waiting state
  if (_ptrThreadPlay)
  {
    // First, the thread must detach itself from Java VM
    _critSect.Leave();
    if (kEventSignaled != _playStartStopEvent.Wait(5000))
    {
      WEBRTC_TRACE(
          kTraceError,
          kTraceAudioDevice,
          _id,
          "%s: Playout thread shutdown timed out, cannot "
          "terminate thread",
          __FUNCTION__);
      // If we close thread anyway, the app will crash
      return -1;
    }
    _critSect.Enter();

    // Close down play thread
    ThreadWrapper* tmpThread = _ptrThreadPlay;
    _ptrThreadPlay = NULL;
    _critSect.Leave();
    _timeEventPlay.Set();
    if (tmpThread->Stop())
    {
      delete tmpThread;
      _jniEnvPlay = NULL;
    }
    else
    {
      WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
                   "  failed to close down the play audio thread");
    }
    _critSect.Enter();

    _playThreadIsInitialized = false;
  }
  _speakerIsInitialized = false;
  _playoutDeviceIsSpecified = false;

  // get the JNI env for this thread
  JNIEnv *env;
  bool isAttached = false;

  // get the JNI env for this thread
  if (_javaVM->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK)
  {
    // try to attach the thread and get the env
    // Attach this thread to JVM
    jint res = _javaVM->AttachCurrentThread(&env, NULL);
    if ((res < 0) || !env)
    {
      WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                   "%s: Could not attach thread to JVM (%d, %p)",
                   __FUNCTION__, res, env);
      return -1;
    }
    isAttached = true;
  }

  // Make method IDs and buffer pointers unusable
  _javaMidPlayAudio = 0;
  _javaDirectPlayBuffer = NULL;

  // Delete the references to the java buffers, this allows the
  // garbage collector to delete them
  env->DeleteGlobalRef(_javaPlayBuffer);
  _javaPlayBuffer = 0;

  // Delete the references to the java object and class, this allows the
  // garbage collector to delete them
  env->DeleteGlobalRef(_javaScObj);
  _javaScObj = 0;
  _javaScClass = 0;

  // Detach this thread if it was attached
  if (isAttached)
  {
    if (_javaVM->DetachCurrentThread() < 0)
    {
      WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
                   "%s: Could not detach thread from JVM", __FUNCTION__);
    }
  }

  _initialized = false;

  return 0;
}

int32_t AudioTrackJni::PlayoutDeviceName(uint16_t index,
                                         char name[kAdmMaxDeviceNameSize],
                                         char guid[kAdmMaxGuidSize]) {
  if (0 != index)
  {
        WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                     "  Device index is out of range [0,0]");
        return -1;
  }

  // Return empty string
  memset(name, 0, kAdmMaxDeviceNameSize);

  if (guid)
  {
    memset(guid, 0, kAdmMaxGuidSize);
    }

  return 0;
}

int32_t AudioTrackJni::SetPlayoutDevice(uint16_t index) {
  if (_playIsInitialized)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "  Playout already initialized");
    return -1;
    }

  if (0 != index)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "  Device index is out of range [0,0]");
    return -1;
  }

  // Do nothing but set a flag, this is to have consistent behavior
  // with other platforms
    _playoutDeviceIsSpecified = true;

    return 0;
}

int32_t AudioTrackJni::SetPlayoutDevice(
    AudioDeviceModule::WindowsDeviceType device) {
  WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
               "  API call not supported on this platform");
  return -1;
}

int32_t AudioTrackJni::PlayoutIsAvailable(bool& available) {  // NOLINT
  available = false;

  // Try to initialize the playout side
  int32_t res = InitPlayout();

  // Cancel effect of initialization
  StopPlayout();

    if (res != -1)
    {
      available = true;
    }

    return res;
}

int32_t AudioTrackJni::InitPlayout() {
  CriticalSectionScoped lock(&_critSect);

    if (!_initialized)
    {
      WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                   "  Not initialized");
      return -1;
    }

    if (_playing)
    {
      WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
                   "  Playout already started");
        return -1;
    }

    if (!_playoutDeviceIsSpecified)
    {
      WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                   "  Playout device is not specified");
      return -1;
    }

    if (_playIsInitialized)
    {
      WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id,
                   "  Playout already initialized");
      return 0;
    }

    // Initialize the speaker
    if (InitSpeaker() == -1)
    {
      WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
                   "  InitSpeaker() failed");
    }

    // get the JNI env for this thread
    JNIEnv *env;
    bool isAttached = false;

    // get the JNI env for this thread
    if (_javaVM->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK)
    {
      WEBRTC_TRACE(kTraceDebug, kTraceAudioDevice, _id,
                   "attaching");

      // try to attach the thread and get the env
      // Attach this thread to JVM
      jint res = _javaVM->AttachCurrentThread(&env, NULL);
      if ((res < 0) || !env)
      {
        WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                     "  Could not attach thread to JVM (%d, %p)", res, env);
        return -1;
      }
      isAttached = true;
    }

    // get the method ID
    jmethodID initPlaybackID = env->GetMethodID(_javaScClass, "InitPlayback",
                                                "(I)I");

    int samplingFreq = 44100;
    if (_samplingFreqOut != 44)
    {
      samplingFreq = _samplingFreqOut * 1000;
    }

    int retVal = -1;

    // Call java sc object method
    jint res = env->CallIntMethod(_javaScObj, initPlaybackID, samplingFreq);
    if (res < 0)
    {
      WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                   "InitPlayback failed (%d)", res);
    }
    else
    {
      // Set the audio device buffer sampling rate
      _ptrAudioBuffer->SetPlayoutSampleRate(_samplingFreqOut * 1000);
      _playIsInitialized = true;
      retVal = 0;
    }

    // Detach this thread if it was attached
    if (isAttached)
    {
      WEBRTC_TRACE(kTraceDebug, kTraceAudioDevice, _id,
                     "detaching");
      if (_javaVM->DetachCurrentThread() < 0)
      {
        WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
                     "  Could not detach thread from JVM");
      }
    }

    return retVal;
}

int32_t AudioTrackJni::StartPlayout() {
  CriticalSectionScoped lock(&_critSect);

  if (!_playIsInitialized)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "  Playout not initialized");
    return -1;
  }

  if (_playing)
    {
      WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id,
                   "  Playout already started");
      return 0;
    }

  // get the JNI env for this thread
  JNIEnv *env;
  bool isAttached = false;

  // get the JNI env for this thread
    if (_javaVM->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK)
    {
      // try to attach the thread and get the env
      // Attach this thread to JVM
      jint res = _javaVM->AttachCurrentThread(&env, NULL);
      if ((res < 0) || !env)
      {
        WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                     "  Could not attach thread to JVM (%d, %p)", res, env);
        return -1;
      }
        isAttached = true;
    }

    // get the method ID
    jmethodID startPlaybackID = env->GetMethodID(_javaScClass, "StartPlayback",
                                                 "()I");

    // Call java sc object method
    jint res = env->CallIntMethod(_javaScObj, startPlaybackID);
    if (res < 0)
    {
        WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                     "StartPlayback failed (%d)", res);
        return -1;
    }

    _playWarning = 0;
    _playError = 0;

    // Signal to playout thread that we want to start
    _startPlay = true;
    _timeEventPlay.Set(); // Release thread from waiting state
    _critSect.Leave();
    // Wait for thread to init
    if (kEventSignaled != _playStartStopEvent.Wait(5000))
    {
      WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                   "  Timeout or error starting");
    }
    _critSect.Enter();

    // Detach this thread if it was attached
    if (isAttached)
    {
      if (_javaVM->DetachCurrentThread() < 0)
      {
        WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
                     "  Could not detach thread from JVM");
      }
    }

    return 0;
}

int32_t AudioTrackJni::StopPlayout() {
  CriticalSectionScoped lock(&_critSect);

  if (!_playIsInitialized)
  {
    WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id,
                 "  Playout is not initialized");
    return 0;
  }

    // get the JNI env for this thread
  JNIEnv *env;
  bool isAttached = false;

  // get the JNI env for this thread
  if (_javaVM->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK)
  {
    // try to attach the thread and get the env
    // Attach this thread to JVM
    jint res = _javaVM->AttachCurrentThread(&env, NULL);
    if ((res < 0) || !env)
        {
          WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                       "  Could not attach thread to JVM (%d, %p)", res, env);
          return -1;
        }
    isAttached = true;
  }

  // get the method ID
  jmethodID stopPlaybackID = env->GetMethodID(_javaScClass, "StopPlayback",
                                              "()I");

  // Call java sc object method
  jint res = env->CallIntMethod(_javaScObj, stopPlaybackID);
  if (res < 0)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "StopPlayback failed (%d)", res);
  }

  _playIsInitialized = false;
  _playing = false;
    _playWarning = 0;
    _playError = 0;

    // Detach this thread if it was attached
    if (isAttached)
    {
      if (_javaVM->DetachCurrentThread() < 0)
      {
        WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
                     "  Could not detach thread from JVM");
      }
    }

    return 0;

}

int32_t AudioTrackJni::InitSpeaker() {
  CriticalSectionScoped lock(&_critSect);

  if (_playing)
  {
    WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
                 "  Playout already started");
    return -1;
  }

    if (!_playoutDeviceIsSpecified)
    {
      WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                   "  Playout device is not specified");
      return -1;
    }

    // Nothing needs to be done here, we use a flag to have consistent
    // behavior with other platforms
    _speakerIsInitialized = true;

    return 0;
}

int32_t AudioTrackJni::SpeakerVolumeIsAvailable(bool& available) {  // NOLINT
  available = true; // We assume we are always be able to set/get volume
  return 0;
}

int32_t AudioTrackJni::SetSpeakerVolume(uint32_t volume) {
  if (!_speakerIsInitialized)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "  Speaker not initialized");
    return -1;
  }
  if (!globalContext)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "  Context is not set");
    return -1;
  }

  // get the JNI env for this thread
  JNIEnv *env;
  bool isAttached = false;

  if (_javaVM->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK)
  {
    // try to attach the thread and get the env
    // Attach this thread to JVM
    jint res = _javaVM->AttachCurrentThread(&env, NULL);
    if ((res < 0) || !env)
    {
      WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                   "  Could not attach thread to JVM (%d, %p)", res, env);
      return -1;
    }
    isAttached = true;
  }

  // get the method ID
  jmethodID setPlayoutVolumeID = env->GetMethodID(_javaScClass,
                                                  "SetPlayoutVolume", "(I)I");

  // call java sc object method
  jint res = env->CallIntMethod(_javaScObj, setPlayoutVolumeID,
                                static_cast<int> (volume));
  if (res < 0)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "SetPlayoutVolume failed (%d)", res);
    return -1;
  }

  // Detach this thread if it was attached
  if (isAttached)
  {
    if (_javaVM->DetachCurrentThread() < 0)
    {
      WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
                   "  Could not detach thread from JVM");
    }
  }

  return 0;
}

int32_t AudioTrackJni::SpeakerVolume(uint32_t& volume) const {  // NOLINT
  if (!_speakerIsInitialized)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "  Speaker not initialized");
    return -1;
  }
  if (!globalContext)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "  Context is not set");
    return -1;
  }

  // get the JNI env for this thread
  JNIEnv *env;
  bool isAttached = false;

  if (_javaVM->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK)
  {
    // try to attach the thread and get the env
    // Attach this thread to JVM
    jint res = _javaVM->AttachCurrentThread(&env, NULL);
    if ((res < 0) || !env)
    {
      WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                   "  Could not attach thread to JVM (%d, %p)", res, env);
      return -1;
    }
    isAttached = true;
  }

  // get the method ID
  jmethodID getPlayoutVolumeID = env->GetMethodID(_javaScClass,
                                                  "GetPlayoutVolume", "()I");

  // call java sc object method
  jint level = env->CallIntMethod(_javaScObj, getPlayoutVolumeID);
  if (level < 0)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "GetPlayoutVolume failed (%d)", level);
    return -1;
  }

  // Detach this thread if it was attached
  if (isAttached)
  {
    if (_javaVM->DetachCurrentThread() < 0)
    {
      WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
                   "  Could not detach thread from JVM");
    }
  }

  volume = static_cast<uint32_t> (level);

  return 0;
}

int32_t AudioTrackJni::MaxSpeakerVolume(uint32_t& maxVolume) const {  // NOLINT
  if (!_speakerIsInitialized)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "  Speaker not initialized");
    return -1;
  }

  maxVolume = _maxSpeakerVolume;

  return 0;
}

int32_t AudioTrackJni::MinSpeakerVolume(uint32_t& minVolume) const {  // NOLINT
  if (!_speakerIsInitialized)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "  Speaker not initialized");
    return -1;
  }
  minVolume = 0;
  return 0;
}

int32_t AudioTrackJni::SpeakerVolumeStepSize(
    uint16_t& stepSize) const {  // NOLINT
  if (!_speakerIsInitialized)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "  Speaker not initialized");
    return -1;
  }

  stepSize = 1;

  return 0;
}

int32_t AudioTrackJni::SpeakerMuteIsAvailable(bool& available) {  // NOLINT
  available = false; // Speaker mute not supported on Android
  return 0;
}

int32_t AudioTrackJni::SetSpeakerMute(bool enable) {
  WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
               "  API call not supported on this platform");
  return -1;
}

int32_t AudioTrackJni::SpeakerMute(bool& /*enabled*/) const {

  WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
               "  API call not supported on this platform");
  return -1;
}

int32_t AudioTrackJni::StereoPlayoutIsAvailable(bool& available) {  // NOLINT
  available = false; // Stereo playout not supported on Android
  return 0;
}

int32_t AudioTrackJni::SetStereoPlayout(bool enable) {
  if (enable)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "  Enabling not available");
    return -1;
  }

  return 0;
}

int32_t AudioTrackJni::StereoPlayout(bool& enabled) const {  // NOLINT
  enabled = false;
  return 0;
}

int32_t AudioTrackJni::SetPlayoutBuffer(
    const AudioDeviceModule::BufferType type,
    uint16_t sizeMS) {
  WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
                 "  API call not supported on this platform");
  return -1;
}

int32_t AudioTrackJni::PlayoutBuffer(
    AudioDeviceModule::BufferType& type,  // NOLINT
    uint16_t& sizeMS) const {  // NOLINT
  type = AudioDeviceModule::kAdaptiveBufferSize;
  sizeMS = _delayPlayout; // Set to current playout delay

    return 0;
}

int32_t AudioTrackJni::PlayoutDelay(uint16_t& delayMS) const {  // NOLINT
  delayMS = _delayPlayout;
  return 0;
}

void AudioTrackJni::AttachAudioBuffer(AudioDeviceBuffer* audioBuffer) {
  CriticalSectionScoped lock(&_critSect);
  _ptrAudioBuffer = audioBuffer;
  // inform the AudioBuffer about default settings for this implementation
  _ptrAudioBuffer->SetPlayoutSampleRate(N_PLAY_SAMPLES_PER_SEC);
  _ptrAudioBuffer->SetPlayoutChannels(N_PLAY_CHANNELS);
}

int32_t AudioTrackJni::SetPlayoutSampleRate(const uint32_t samplesPerSec) {
  if (samplesPerSec > 48000 || samplesPerSec < 8000)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "  Invalid sample rate");
    return -1;
    }

  // set the playout sample rate to use
  if (samplesPerSec == 44100)
  {
    _samplingFreqOut = 44;
  }
  else
  {
    _samplingFreqOut = samplesPerSec / 1000;
  }

  // Update the AudioDeviceBuffer
  _ptrAudioBuffer->SetPlayoutSampleRate(samplesPerSec);

  return 0;
}

bool AudioTrackJni::PlayoutWarning() const {
  return (_playWarning > 0);
}

bool AudioTrackJni::PlayoutError() const {
  return (_playError > 0);
}

void AudioTrackJni::ClearPlayoutWarning() {
  _playWarning = 0;
}

void AudioTrackJni::ClearPlayoutError() {
  _playError = 0;
}

int32_t AudioTrackJni::SetLoudspeakerStatus(bool enable) {
  if (!globalContext)
  {
    WEBRTC_TRACE(kTraceError, kTraceUtility, -1,
                 "  Context is not set");
    return -1;
  }

  // get the JNI env for this thread
  JNIEnv *env;
    bool isAttached = false;

    if (_javaVM->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK)
    {
      // try to attach the thread and get the env
      // Attach this thread to JVM
      jint res = _javaVM->AttachCurrentThread(&env, NULL);

      // Get the JNI env for this thread
      if ((res < 0) || !env)
      {
            WEBRTC_TRACE(kTraceError, kTraceUtility, -1,
                         "  Could not attach thread to JVM (%d, %p)", res, env);
            return -1;
      }
      isAttached = true;
    }

    // get the method ID
    jmethodID setPlayoutSpeakerID = env->GetMethodID(_javaScClass,
                                                     "SetPlayoutSpeaker",
                                                     "(Z)I");

    // call java sc object method
    jint res = env->CallIntMethod(_javaScObj, setPlayoutSpeakerID, enable);
    if (res < 0)
    {
      WEBRTC_TRACE(kTraceError, kTraceUtility, -1,
                   "  SetPlayoutSpeaker failed (%d)", res);
      return -1;
    }

    _loudSpeakerOn = enable;

    // Detach this thread if it was attached
    if (isAttached)
    {
      if (_javaVM->DetachCurrentThread() < 0)
      {
        WEBRTC_TRACE(kTraceWarning, kTraceUtility, -1,
                     "  Could not detach thread from JVM");
      }
    }

    return 0;
}

int32_t AudioTrackJni::GetLoudspeakerStatus(bool& enabled) const {  // NOLINT
  enabled = _loudSpeakerOn;
  return 0;
}

int32_t AudioTrackJni::InitJavaResources() {
  // todo: Check if we already have created the java object
  _javaVM = globalJvm;
  _javaScClass = globalScClass;

  // use the jvm that has been set
  if (!_javaVM)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "%s: Not a valid Java VM pointer", __FUNCTION__);
    return -1;
  }

  // get the JNI env for this thread
  JNIEnv *env;
  bool isAttached = false;

  // get the JNI env for this thread
  if (_javaVM->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK)
  {
    // try to attach the thread and get the env
    // Attach this thread to JVM
    jint res = _javaVM->AttachCurrentThread(&env, NULL);
    if ((res < 0) || !env)
    {
      WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                   "%s: Could not attach thread to JVM (%d, %p)",
                   __FUNCTION__, res, env);
      return -1;
    }
    isAttached = true;
  }

  WEBRTC_TRACE(kTraceDebug, kTraceAudioDevice, _id,
               "get method id");

  // get the method ID for the void(void) constructor
  jmethodID cid = env->GetMethodID(_javaScClass, "<init>", "()V");
  if (cid == NULL)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "%s: could not get constructor ID", __FUNCTION__);
    return -1; /* exception thrown */
  }

  WEBRTC_TRACE(kTraceDebug, kTraceAudioDevice, _id,
               "construct object", __FUNCTION__);

  // construct the object
  jobject javaScObjLocal = env->NewObject(_javaScClass, cid);
  if (!javaScObjLocal)
  {
    WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
                 "%s: could not create Java sc object", __FUNCTION__);
    return -1;
  }

  // Create a reference to the object (to tell JNI that we are referencing it
  // after this function has returned).
  _javaScObj = env->NewGlobalRef(javaScObjLocal);
  if (!_javaScObj)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "%s: could not create Java sc object reference",
                 __FUNCTION__);
    return -1;
  }

  // Delete local object ref, we only use the global ref.
  env->DeleteLocalRef(javaScObjLocal);

  //////////////////////
  // AUDIO MANAGEMENT

  // This is not mandatory functionality
  if (globalContext) {
    jfieldID context_id = env->GetFieldID(globalScClass,
                                          "_context",
                                          "Landroid/content/Context;");
    if (!context_id) {
      WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                   "%s: could not get _context id", __FUNCTION__);
      return -1;
    }

    env->SetObjectField(_javaScObj, context_id, globalContext);
    jobject javaContext = env->GetObjectField(_javaScObj, context_id);
    if (!javaContext) {
      WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                   "%s: could not set or get _context", __FUNCTION__);
      return -1;
    }
  }
  else {
    WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
                 "%s: did not set Context - some functionality is not "
                 "supported",
                 __FUNCTION__);
  }

  /////////////
  // PLAYOUT

  // Get play buffer field ID.
  jfieldID fidPlayBuffer = env->GetFieldID(_javaScClass, "_playBuffer",
                                           "Ljava/nio/ByteBuffer;");
  if (!fidPlayBuffer)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "%s: could not get play buffer fid", __FUNCTION__);
    return -1;
  }

  // Get play buffer object.
  jobject javaPlayBufferLocal =
      env->GetObjectField(_javaScObj, fidPlayBuffer);
  if (!javaPlayBufferLocal)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "%s: could not get play buffer", __FUNCTION__);
    return -1;
  }

  // Create a global reference to the object (to tell JNI that we are
  // referencing it after this function has returned)
  // NOTE: we are referencing it only through the direct buffer (see below).
  _javaPlayBuffer = env->NewGlobalRef(javaPlayBufferLocal);
  if (!_javaPlayBuffer)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "%s: could not get play buffer reference", __FUNCTION__);
    return -1;
  }

  // Delete local object ref, we only use the global ref.
  env->DeleteLocalRef(javaPlayBufferLocal);

  // Get direct buffer.
  _javaDirectPlayBuffer = env->GetDirectBufferAddress(_javaPlayBuffer);
  if (!_javaDirectPlayBuffer)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "%s: could not get direct play buffer", __FUNCTION__);
    return -1;
  }

  // Get the play audio method ID.
  _javaMidPlayAudio = env->GetMethodID(_javaScClass, "PlayAudio", "(I)I");
  if (!_javaMidPlayAudio)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "%s: could not get play audio mid", __FUNCTION__);
    return -1;
  }

  // Detach this thread if it was attached.
  if (isAttached)
  {
    if (_javaVM->DetachCurrentThread() < 0)
    {
      WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
                   "%s: Could not detach thread from JVM", __FUNCTION__);
    }
  }

  return 0;

}

int32_t AudioTrackJni::InitSampleRate() {
  int samplingFreq = 44100;
  jint res = 0;

  // get the JNI env for this thread
  JNIEnv *env;
  bool isAttached = false;

  // get the JNI env for this thread
  if (_javaVM->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK)
  {
    // try to attach the thread and get the env
    // Attach this thread to JVM
    jint res = _javaVM->AttachCurrentThread(&env, NULL);
    if ((res < 0) || !env)
    {
      WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                   "%s: Could not attach thread to JVM (%d, %p)",
                   __FUNCTION__, res, env);
      return -1;
    }
    isAttached = true;
  }

  // get the method ID
  jmethodID initPlaybackID = env->GetMethodID(_javaScClass, "InitPlayback",
                                              "(I)I");

  if (_samplingFreqOut > 0)
  {
    // read the configured sampling rate
    samplingFreq = 44100;
    if (_samplingFreqOut != 44)
    {
      samplingFreq = _samplingFreqOut * 1000;
    }
    WEBRTC_TRACE(kTraceStateInfo, kTraceAudioDevice, _id,
                 "  Trying configured playback sampling rate %d",
                 samplingFreq);
  }
  else
  {
    // set the preferred sampling frequency
    if (samplingFreq == 8000)
    {
      // try 16000
      samplingFreq = 16000;
    }
    // else use same as recording
  }

  bool keepTrying = true;
  while (keepTrying)
  {
    // call java sc object method
    res = env->CallIntMethod(_javaScObj, initPlaybackID, samplingFreq);
    if (res < 0)
    {
      switch (samplingFreq)
      {
        case 44100:
          samplingFreq = 16000;
          break;
        case 16000:
          samplingFreq = 8000;
          break;
        default: // error
          WEBRTC_TRACE(kTraceError,
                       kTraceAudioDevice, _id,
                       "InitPlayback failed (%d)", res);
          return -1;
      }
    }
    else
    {
      keepTrying = false;
    }
  }

  // Store max playout volume
  _maxSpeakerVolume = static_cast<uint32_t> (res);
  if (_maxSpeakerVolume < 1)
  {
    WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
                 "  Did not get valid max speaker volume value (%d)",
                 _maxSpeakerVolume);
  }

  // set the playback sample rate to use
  if (samplingFreq == 44100)
  {
    _samplingFreqOut = 44;
  }
  else
  {
    _samplingFreqOut = samplingFreq / 1000;
  }

  WEBRTC_TRACE(kTraceStateInfo, kTraceAudioDevice, _id,
               "Playback sample rate set to (%d)", _samplingFreqOut);

  // get the method ID
  jmethodID stopPlaybackID = env->GetMethodID(_javaScClass, "StopPlayback",
                                              "()I");

  // Call java sc object method
  res = env->CallIntMethod(_javaScObj, stopPlaybackID);
  if (res < 0)
  {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                 "StopPlayback failed (%d)", res);
  }

  // Detach this thread if it was attached
  if (isAttached)
  {
    if (_javaVM->DetachCurrentThread() < 0)
    {
      WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
                   "%s: Could not detach thread from JVM", __FUNCTION__);
    }
  }

  return 0;

}

bool AudioTrackJni::PlayThreadFunc(void* pThis)
{
  return (static_cast<AudioTrackJni*> (pThis)->PlayThreadProcess());
}

bool AudioTrackJni::PlayThreadProcess()
{
  if (!_playThreadIsInitialized)
  {
    // Do once when thread is started

    // Attach this thread to JVM and get the JNI env for this thread
    jint res = _javaVM->AttachCurrentThread(&_jniEnvPlay, NULL);
    if ((res < 0) || !_jniEnvPlay)
    {
            WEBRTC_TRACE(kTraceCritical, kTraceAudioDevice,
                         _id,
                         "Could not attach playout thread to JVM (%d, %p)",
                         res, _jniEnvPlay);
            return false; // Close down thread
    }

    _playThreadIsInitialized = true;
  }

  if (!_playing)
    {
      switch (_timeEventPlay.Wait(1000))
      {
        case kEventSignaled:
          WEBRTC_TRACE(kTraceDebug, kTraceAudioDevice,
                       _id, "Playout thread event signal");
          break;
        case kEventError:
          WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice,
                       _id, "Playout thread event error");
                return true;
        case kEventTimeout:
          WEBRTC_TRACE(kTraceDebug, kTraceAudioDevice,
                       _id, "Playout thread event timeout");
          return true;
      }
    }

  Lock();

  if (_startPlay)
    {
      WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id,
                   "_startPlay true, performing initial actions");
      _startPlay = false;
      _playing = true;
      _playWarning = 0;
      _playError = 0;
      _playStartStopEvent.Set();
      WEBRTC_TRACE(kTraceDebug, kTraceAudioDevice, _id,
                   "Sent signal");
    }

  if (_playing)
  {
    int8_t playBuffer[2 * 480]; // Max 10 ms @ 48 kHz / 16 bit
    uint32_t samplesToPlay = _samplingFreqOut * 10;

    // ask for new PCM data to be played out using the AudioDeviceBuffer
    // ensure that this callback is executed without taking the
    // audio-thread lock
    UnLock();
    uint32_t nSamples =
                _ptrAudioBuffer->RequestPlayoutData(samplesToPlay);
    Lock();

    // Check again since play may have stopped during unlocked period
    if (!_playing)
    {
      UnLock();
      return true;
    }

    nSamples = _ptrAudioBuffer->GetPlayoutData(playBuffer);
        if (nSamples != samplesToPlay)
        {
          WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                       "  invalid number of output samples(%d)", nSamples);
          _playWarning = 1;
        }

        // Copy data to our direct buffer (held by java sc object)
        // todo: Give _javaDirectPlayBuffer directly to VoE?
        memcpy(_javaDirectPlayBuffer, playBuffer, nSamples * 2);

        UnLock();

        // Call java sc object method to process data in direct buffer
        // Will block until data has been put in OS playout buffer
        // (see java sc class)
        jint res = _jniEnvPlay->CallIntMethod(_javaScObj, _javaMidPlayAudio,
                                              2 * nSamples);
        if (res < 0)
        {
          WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
                       "PlayAudio failed (%d)", res);
            _playWarning = 1;
        }
        else if (res > 0)
        {
          // we are not recording and have got a delay value from playback
          _delayPlayout = res / _samplingFreqOut;
        }
        Lock();

  }  // _playing

  if (_shutdownPlayThread)
  {
    WEBRTC_TRACE(kTraceDebug, kTraceAudioDevice, _id,
                 "Detaching thread from Java VM");

    // Detach thread from Java VM
    if (_javaVM->DetachCurrentThread() < 0)
    {
            WEBRTC_TRACE(kTraceCritical, kTraceAudioDevice,
                         _id, "Could not detach playout thread from JVM");
            _shutdownPlayThread = false;
            // If we say OK (i.e. set event) and close thread anyway,
            // app will crash
    }
    else
    {
      _jniEnvPlay = NULL;
      _shutdownPlayThread = false;
      _playStartStopEvent.Set(); // Signal to Terminate() that we are done
            WEBRTC_TRACE(kTraceDebug, kTraceAudioDevice, _id,
                         "Sent signal");
    }
  }

  UnLock();
  return true;
}

}  // namespace webrtc


text:
<?php

namespace Fridge\DBAL\Debug;

/**
 * Query debugger.
 *
 * @author GeLo <geloen.eric@gmail.com>
 */
class QueryDebugger
{
    /** @var string */
    private $query;

    /** @var array */
    private $parameters;

    /** @var array */
    private $types;

    /** @var float */
    private $time;

    /** @var float */
    private $start;

    /**
     * Creates and starts a query debugger.
     *
     * @param string $query      The debugged query
     * @param array  $parameters The debugged parameters.
     * @param array  $types      The debugged types.
     */
    public function __construct($query, array $parameters, array $types)
    {
        $this->query = $query;
        $this->parameters = $parameters;
        $this->types = $types;

        $this->start = microtime(true);
    }

    /**
     * Stops the debug.
     */
    public function stop()
    {
        $this->time = microtime(true) - $this->start;
    }

    /**
     * Gets the debugged query.
     *
     * @return string The debugged query.
     */
    public function getQuery()
    {
        return $this->query;
    }

    /**
     * Gets the debugged parameters.
     *
     * @return array The debugged parameters.
     */
    public function getParameters()
    {
        return $this->parameters;
    }

    /**
     * Gets the debugged types.
     *
     * @return array The debugged types.
     */
    public function getTypes()
    {
        return $this->types;
    }

    /**
     * Gets the execution time of the query in ms.
     *
     * @return float The execution time of the query.
     */
    public function getTime()
    {
        return $this->time;
    }
}

redpajama_set_name: RedPajamaGithub


text:
@interface FLAbstractViewTransition : FLAbstractAnimation {
@private
    SDKView* _viewToShow;
    SDKView* _viewToHide;
}

- (void) startShowingView:(SDKView*) viewToShow
               viewToHide:(SDKView*) viewToHide
               completion:(fl_block_t) completion;

// overrides
- (void) prepareTransition:(CALayer*) showLayer hideLayer:(CALayer*) hideLayer;
- (void) commitTransition:(CALayer*) showLayer hideLayer:(CALayer*) hideLayer;
- (void) finishTransition:(CALayer*) showLayer hideLayer:(CALayer*) hideLayer;

@end

@interface FLViewTransition : FLAbstractViewTransition {
@private
    FLAnimation* _showAnimation;
    FLAnimation* _hideAnimation;
}
@property (readwrite, strong, nonatomic) FLAnimation* showAnimation;
@property (readwrite, strong, nonatomic) FLAnimation* hideAnimation;

@end

@interface FLBatchViewTransition : FLAbstractViewTransition {
@private
    NSMutableArray* _showAnimations;
    NSMutableArray* _hideAnimations;
}

- (void) addShowAnimation:(FLAnimation*) animation;
- (void) addHideAnimation:(FLAnimation*) animation;

@end


text:
var pkgcloud = require('pkgcloud'),
  logging = require('../../../common/logging'),
  config = require('../../../common/config'),
  _ = require('underscore');

var log = logging.getLogger(process.env.PKGCLOUD_LOG_LEVEL || 'debug');

var client = pkgcloud.providers.rackspace.loadbalancer.createClient(config.getConfig('rackspace', 1));

client.on('log::*', logging.logFunction);

client.getLoadBalancer(process.argv[2], function (err, lb) {
  if (err) {
    log.error(err);
    return;
  }

  lb.getVirtualIps(function (err, ips) {
    if (err) {
      log.error(err);
      return;
    }

    log.info(ips);
  });
});


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Class net.jini.lease.LeaseRenewalManager.Init (River-Internet vtrunk API Documentation (internals))</title>
<meta name="date" content="2016-03-28">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
net.jini.lease.LeaseRenewalManager.Init

Packages that use LeaseRenewalManager.Init

Package
Description

net.jini.lease

Standard service and utility classes for managing leases.

Uses of LeaseRenewalManager.Init in net.jini.lease

Methods in net.jini.lease that return LeaseRenewalManager.Init

Modifier and Type
Method and Description

private static LeaseRenewalManager.Init
LeaseRenewalManager.init(Configuration config)

Constructors in net.jini.lease with parameters of type LeaseRenewalManager.Init

Constructor and Description

LeaseRenewalManager(LeaseRenewalManager.Init init)

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright 2007-2013, multiple authors.
Licensed under the Apache License, Version 2.0, see the NOTICE file for attributions.


text:
import sys
from twisted.python import log
from twisted.internet import reactor
from twisted.web.static import File
from twisted.web.websocket import WebSocketHandler, WebSocketSite

class Echohandler(WebSocketHandler):
    def frameReceived(self, frame):
        log.msg("Received frame '%s'" % frame)
        self.transport.write(frame + "\n")

def main():
    log.startLogging(sys.stdout)
    root = File("/home/slashroot/workspace/slashrootcafe/push/websocket_server")
    site = WebSocketSite(root)
    site.addHandler("ws/echo", Echohandler)
    reactor.listenTCP(7000, site)
    reactor.run()

if __name__ == "__main__":
    main()


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ParserClothingSite.PageInfo
{
    public interface IPageAction<Z> where Z : IContainerForBlock<PageSimpleBlock>
    {
        IEnumerable<Z> GetCollectionBlock(Func<Z, bool> _predicate, Page<Z> _page);
        IEnumerable<Page<Z>> GetIterableChildBlock(Page<Z> _page);
    }
}


text:
#include "third_party/blink/renderer/modules/webaudio/audio_node.h"

#include <inttypes.h>

#include "third_party/blink/public/platform/modules/webrtc/webrtc_logging.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_audio_node_options.h"
#include "third_party/blink/renderer/modules/webaudio/audio_graph_tracer.h"
#include "third_party/blink/renderer/modules/webaudio/audio_handler.h"
#include "third_party/blink/renderer/modules/webaudio/audio_node_output.h"
#include "third_party/blink/renderer/modules/webaudio/audio_node_wiring.h"
#include "third_party/blink/renderer/modules/webaudio/audio_param.h"
#include "third_party/blink/renderer/modules/webaudio/base_audio_context.h"
#include "third_party/blink/renderer/platform/bindings/exception_messages.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"

#if DEBUG_AUDIONODE_REFERENCES
#include <stdio.h>
#endif

namespace blink {

AudioNode::AudioNode(BaseAudioContext& context)
    : InspectorHelperMixin(context.GraphTracer(), context.Uuid()),
      context_(context),
      deferred_task_handler_(&context.GetDeferredTaskHandler()),
      handler_(nullptr) {}

AudioNode::~AudioNode() {
  // The graph lock is required to destroy the handler. And we can't use
  // `context_` to touch it, since that object may also be a dead heap object.
  {
    DeferredTaskHandler::GraphAutoLocker locker(*deferred_task_handler_);
    handler_ = nullptr;
  }
}

void AudioNode::Dispose() {
  DCHECK(IsMainThread());
#if DEBUG_AUDIONODE_REFERENCES
  fprintf(stderr, "[%16p]: %16p: %2d: AudioNode::dispose %16p @%g\n", context(),
          this, Handler().GetNodeType(), handler_.get(),
          context()->currentTime());
#endif
  BaseAudioContext::GraphAutoLocker locker(context());
  Handler().Dispose();

  // Add the handler to the orphan list.  This keeps the handler alive until it
  // can be deleted at a safe point (in pre/post handler task).  If the graph is
  // being processed, the handler must be added.  If the context is suspended,
  // the handler still needs to be added in case the context is resumed.
  DCHECK(context());
  if (context()->IsPullingAudioGraph() ||
      context()->ContextState() == BaseAudioContext::kSuspended) {
    context()->GetDeferredTaskHandler().AddRenderingOrphanHandler(
        std::move(handler_));
  }

  // Notify the inspector that this node is going away. The actual clean up
  // will be done in the subclass implementation.
  ReportWillBeDestroyed();
}

void AudioNode::SetHandler(scoped_refptr<AudioHandler> handler) {
  DCHECK(handler);
  handler_ = std::move(handler);

  // Unless the node is an AudioDestinationNode, notify the inspector that the
  // construction is completed. The actual report will be done in the subclass
  // implementation. (A destination node is owned by the context and will be
  // reported by it.)
  if (handler_->GetNodeType() != AudioHandler::NodeType::kNodeTypeDestination) {
    ReportDidCreate();
  }

#if DEBUG_AUDIONODE_REFERENCES
  fprintf(stderr, "[%16p]: %16p: %2d: AudioNode::AudioNode %16p\n", context(),
          this, handler_->GetNodeType(), handler_.get());
#endif
}

bool AudioNode::ContainsHandler() const {
  return handler_.get();
}

AudioHandler& AudioNode::Handler() const {
  return *handler_;
}

void AudioNode::Trace(Visitor* visitor) const {
  visitor->Trace(context_);
  visitor->Trace(connected_nodes_);
  visitor->Trace(connected_params_);
  InspectorHelperMixin::Trace(visitor);
  EventTargetWithInlineData::Trace(visitor);
}

void AudioNode::HandleChannelOptions(const AudioNodeOptions* options,
                                     ExceptionState& exception_state) {
  DCHECK(IsMainThread());

  if (options->hasChannelCount()) {
    setChannelCount(options->channelCount(), exception_state);
  }
  if (options->hasChannelCountMode()) {
    setChannelCountMode(options->channelCountMode(), exception_state);
  }
  if (options->hasChannelInterpretation()) {
    setChannelInterpretation(options->channelInterpretation(), exception_state);
  }
}

String AudioNode::GetNodeName() const {
  return Handler().NodeTypeName();
}

BaseAudioContext* AudioNode::context() const {
  return context_;
}

AudioNode* AudioNode::connect(AudioNode* destination,
                              unsigned output_index,
                              unsigned input_index,
                              ExceptionState& exception_state) {
  DCHECK(IsMainThread());
  BaseAudioContext::GraphAutoLocker locker(context());

  context()->WarnForConnectionIfContextClosed();

  if (!destination) {
    exception_state.ThrowDOMException(DOMExceptionCode::kSyntaxError,
                                      "invalid destination node.");
    return nullptr;
  }

  // Sanity check input and output indices.
  if (output_index >= numberOfOutputs()) {
    exception_state.ThrowDOMException(
        DOMExceptionCode::kIndexSizeError,
        "output index (" + String::Number(output_index) +
            ") exceeds number of outputs (" +
            String::Number(numberOfOutputs()) + ").");
    return nullptr;
  }

  if (destination && input_index >= destination->numberOfInputs()) {
    exception_state.ThrowDOMException(
        DOMExceptionCode::kIndexSizeError,
        "input index (" + String::Number(input_index) +
            ") exceeds number of inputs (" +
            String::Number(destination->numberOfInputs()) + ").");
    return nullptr;
  }

  if (context() != destination->context()) {
    exception_state.ThrowDOMException(
        DOMExceptionCode::kInvalidAccessError,
        "cannot connect to an AudioNode "
        "belonging to a different audio context.");
    return nullptr;
  }

  // ScriptProcessorNodes with 0 output channels can't be connected to any
  // destination.  If there are no output channels, what would the destination
  // receive?  Just disallow this.
  if (Handler().GetNodeType() == AudioHandler::kNodeTypeScriptProcessor &&
      Handler().NumberOfOutputChannels() == 0) {
    exception_state.ThrowDOMException(DOMExceptionCode::kInvalidAccessError,
                                      "cannot connect a ScriptProcessorNode "
                                      "with 0 output channels to any "
                                      "destination node.");
    return nullptr;
  }

  SendLogMessage(String::Format(
      "%s({output=[index:%u, type:%s, handler:0x%" PRIXPTR
      "]} --> "
      "{input=[index:%u, type:%s, handler:0x%" PRIXPTR "]})",
      __func__, output_index, Handler().NodeTypeName().Utf8().c_str(),
      reinterpret_cast<uintptr_t>(&Handler()), input_index,
      destination->Handler().NodeTypeName().Utf8().c_str(),
      reinterpret_cast<uintptr_t>(&destination->Handler())));

  AudioNodeWiring::Connect(Handler().Output(output_index),
                           destination->Handler().Input(input_index));
  if (!connected_nodes_[output_index]) {
    connected_nodes_[output_index] =
        MakeGarbageCollected<HeapHashSet<Member<AudioNode>>>();
  }
  connected_nodes_[output_index]->insert(destination);

  Handler().UpdatePullStatusIfNeeded();

  GraphTracer().DidConnectNodes(this, destination, output_index, input_index);

  return destination;
}

void AudioNode::connect(AudioParam* param,
                        unsigned output_index,
                        ExceptionState& exception_state) {
  DCHECK(IsMainThread());
  BaseAudioContext::GraphAutoLocker locker(context());

  context()->WarnForConnectionIfContextClosed();

  if (!param) {
    exception_state.ThrowDOMException(DOMExceptionCode::kSyntaxError,
                                      "invalid AudioParam.");
    return;
  }

  if (output_index >= numberOfOutputs()) {
    exception_state.ThrowDOMException(
        DOMExceptionCode::kIndexSizeError,
        "output index (" + String::Number(output_index) +
            ") exceeds number of outputs (" +
            String::Number(numberOfOutputs()) + ").");
    return;
  }

  if (context() != param->Context()) {
    exception_state.ThrowDOMException(
        DOMExceptionCode::kInvalidAccessError,
        "cannot connect to an AudioParam "
        "belonging to a different audio context.");
    return;
  }

  AudioNodeWiring::Connect(Handler().Output(output_index), param->Handler());
  if (!connected_params_[output_index]) {
    connected_params_[output_index] =
        MakeGarbageCollected<HeapHashSet<Member<AudioParam>>>();
  }
  connected_params_[output_index]->insert(param);

  Handler().UpdatePullStatusIfNeeded();

  GraphTracer().DidConnectNodeParam(this, param, output_index);
}

void AudioNode::DisconnectAllFromOutput(unsigned output_index) {
  Handler().Output(output_index).DisconnectAll();
  connected_nodes_[output_index] = nullptr;
  connected_params_[output_index] = nullptr;
}

bool AudioNode::DisconnectFromOutputIfConnected(
    unsigned output_index,
    AudioNode& destination,
    unsigned input_index_of_destination) {
  AudioNodeOutput& output = Handler().Output(output_index);
  AudioNodeInput& input =
      destination.Handler().Input(input_index_of_destination);
  if (!AudioNodeWiring::IsConnected(output, input)) {
    return false;
  }
  AudioNodeWiring::Disconnect(output, input);
  connected_nodes_[output_index]->erase(&destination);
  return true;
}

bool AudioNode::DisconnectFromOutputIfConnected(unsigned output_index,
                                                AudioParam& param) {
  AudioNodeOutput& output = Handler().Output(output_index);
  if (!AudioNodeWiring::IsConnected(output, param.Handler())) {
    return false;
  }
  AudioNodeWiring::Disconnect(output, param.Handler());
  connected_params_[output_index]->erase(&param);
  return true;
}

void AudioNode::disconnect() {
  DCHECK(IsMainThread());
  BaseAudioContext::GraphAutoLocker locker(context());

  // Disconnect all outgoing connections.
  for (unsigned i = 0; i < numberOfOutputs(); ++i) {
    DisconnectAllFromOutput(i);
  }

  Handler().UpdatePullStatusIfNeeded();

  GraphTracer().DidDisconnectNodes(this);
}

void AudioNode::disconnect(unsigned output_index,
                           ExceptionState& exception_state) {
  DCHECK(IsMainThread());
  BaseAudioContext::GraphAutoLocker locker(context());

  // Sanity check on the output index.
  if (output_index >= numberOfOutputs()) {
    exception_state.ThrowDOMException(
        DOMExceptionCode::kIndexSizeError,
        ExceptionMessages::IndexOutsideRange(
            "output index", output_index, 0u,
            ExceptionMessages::kInclusiveBound, numberOfOutputs() - 1,
            ExceptionMessages::kInclusiveBound));
    return;
  }
  // Disconnect all outgoing connections from the given output.
  DisconnectAllFromOutput(output_index);

  Handler().UpdatePullStatusIfNeeded();

  GraphTracer().DidDisconnectNodes(this, nullptr, output_index);
}

void AudioNode::disconnect(AudioNode* destination,
                           ExceptionState& exception_state) {
  DCHECK(IsMainThread());

  if (context() != destination->context()) {
    exception_state.ThrowDOMException(
        DOMExceptionCode::kInvalidAccessError,
        "cannot disconnect from an AudioNode "
        "belonging to a different audio context.");
    return;
  }

  BaseAudioContext::GraphAutoLocker locker(context());

  unsigned number_of_disconnections = 0;

  // FIXME: Can this be optimized? ChannelSplitter and ChannelMerger can have
  // 32 ports and that requires 1024 iterations to validate entire connections.
  for (unsigned output_index = 0; output_index < numberOfOutputs();
       ++output_index) {
    for (unsigned input_index = 0;
         input_index < destination->Handler().NumberOfInputs(); ++input_index) {
      if (DisconnectFromOutputIfConnected(output_index, *destination,
                                          input_index)) {
        number_of_disconnections++;
      }
    }
  }

  // If there is no connection to the destination, throw an exception.
  if (number_of_disconnections == 0) {
    exception_state.ThrowDOMException(
        DOMExceptionCode::kInvalidAccessError,
        "the given destination is not connected.");
    return;
  }

  Handler().UpdatePullStatusIfNeeded();

  GraphTracer().DidDisconnectNodes(this, destination);
}

void AudioNode::disconnect(AudioNode* destination,
                           unsigned output_index,
                           ExceptionState& exception_state) {
  DCHECK(IsMainThread());

  if (context() != destination->context()) {
    exception_state.ThrowDOMException(
        DOMExceptionCode::kInvalidAccessError,
        "cannot disconnect from an AudioNode "
        "belonging to a different audio context.");
    return;
  }

  BaseAudioContext::GraphAutoLocker locker(context());

  if (output_index >= numberOfOutputs()) {
    // The output index is out of range. Throw an exception.
    exception_state.ThrowDOMException(
        DOMExceptionCode::kIndexSizeError,
        ExceptionMessages::IndexOutsideRange(
            "output index", output_index, 0u,
            ExceptionMessages::kInclusiveBound, numberOfOutputs() - 1,
            ExceptionMessages::kInclusiveBound));
    return;
  }

  // If the output index is valid, proceed to disconnect.
  unsigned number_of_disconnections = 0;
  // Sanity check on destination inputs and disconnect when possible.
  for (unsigned input_index = 0; input_index < destination->numberOfInputs();
       ++input_index) {
    if (DisconnectFromOutputIfConnected(output_index, *destination,
                                        input_index)) {
      number_of_disconnections++;
    }
  }

  // If there is no connection to the destination, throw an exception.
  if (number_of_disconnections == 0) {
    exception_state.ThrowDOMException(
        DOMExceptionCode::kInvalidAccessError,
        "output (" + String::Number(output_index) +
            ") is not connected to the given destination.");
  }

  Handler().UpdatePullStatusIfNeeded();

  GraphTracer().DidDisconnectNodes(this, destination, output_index);
}

void AudioNode::disconnect(AudioNode* destination,
                           unsigned output_index,
                           unsigned input_index,
                           ExceptionState& exception_state) {
  DCHECK(IsMainThread());

  if (context() != destination->context()) {
    exception_state.ThrowDOMException(
        DOMExceptionCode::kInvalidAccessError,
        "cannot disconnect from an AudioNode "
        "belonging to a different audio context.");
    return;
  }

  BaseAudioContext::GraphAutoLocker locker(context());

  if (output_index >= numberOfOutputs()) {
    exception_state.ThrowDOMException(
        DOMExceptionCode::kIndexSizeError,
        ExceptionMessages::IndexOutsideRange(
            "output index", output_index, 0u,
            ExceptionMessages::kInclusiveBound, numberOfOutputs() - 1,
            ExceptionMessages::kInclusiveBound));
    return;
  }

  if (input_index >= destination->Handler().NumberOfInputs()) {
    exception_state.ThrowDOMException(
        DOMExceptionCode::kIndexSizeError,
        ExceptionMessages::IndexOutsideRange(
            "input index", input_index, 0u, ExceptionMessages::kInclusiveBound,
            destination->numberOfInputs() - 1,
            ExceptionMessages::kInclusiveBound));
    return;
  }

  // If both indices are valid, proceed to disconnect.
  if (!DisconnectFromOutputIfConnected(output_index, *destination,
                                       input_index)) {
    exception_state.ThrowDOMException(
        DOMExceptionCode::kInvalidAccessError,
        "output (" + String::Number(output_index) +
            ") is not connected to the input (" + String::Number(input_index) +
            ") of the destination.");
    return;
  }

  Handler().UpdatePullStatusIfNeeded();

  GraphTracer().DidDisconnectNodes(
      this, destination, output_index, input_index);
}

void AudioNode::disconnect(AudioParam* destination_param,
                           ExceptionState& exception_state) {
  DCHECK(IsMainThread());

  if (context() != destination_param->Context()) {
    exception_state.ThrowDOMException(
        DOMExceptionCode::kInvalidAccessError,
        "cannot disconnect from an AudioParam "
        "belonging to a different audio context.");
    return;
  }

  BaseAudioContext::GraphAutoLocker locker(context());

  // The number of disconnection made.
  unsigned number_of_disconnections = 0;

  // Check if the node output is connected the destination AudioParam.
  // Disconnect if connected and increase `number_of_disconnections` by 1.
  for (unsigned output_index = 0; output_index < Handler().NumberOfOutputs();
       ++output_index) {
    if (DisconnectFromOutputIfConnected(output_index, *destination_param)) {
      number_of_disconnections++;
    }
  }

  // Throw an exception when there is no valid connection to the destination.
  if (number_of_disconnections == 0) {
    exception_state.ThrowDOMException(DOMExceptionCode::kInvalidAccessError,
                                      "the given AudioParam is not connected.");
    return;
  }

  Handler().UpdatePullStatusIfNeeded();

  GraphTracer().DidDisconnectNodeParam(this, destination_param);
}

void AudioNode::disconnect(AudioParam* destination_param,
                           unsigned output_index,
                           ExceptionState& exception_state) {
  DCHECK(IsMainThread());
  BaseAudioContext::GraphAutoLocker locker(context());

  if (context() != destination_param->Context()) {
    exception_state.ThrowDOMException(
        DOMExceptionCode::kInvalidAccessError,
        "cannot disconnect from an AudioParam belonging to a different "
        "BaseAudioContext.");
    return;
  }

  if (output_index >= Handler().NumberOfOutputs()) {
    // The output index is out of range. Throw an exception.
    exception_state.ThrowDOMException(
        DOMExceptionCode::kIndexSizeError,
        ExceptionMessages::IndexOutsideRange(
            "output index", output_index, 0u,
            ExceptionMessages::kInclusiveBound, numberOfOutputs() - 1,
            ExceptionMessages::kInclusiveBound));
    return;
  }

  // If the output index is valid, proceed to disconnect.
  if (!DisconnectFromOutputIfConnected(output_index, *destination_param)) {
    exception_state.ThrowDOMException(
        DOMExceptionCode::kInvalidAccessError,
        "specified destination AudioParam and node output (" +
            String::Number(output_index) + ") are not connected.");
    return;
  }

  Handler().UpdatePullStatusIfNeeded();

  GraphTracer().DidDisconnectNodeParam(this, destination_param, output_index);
}

unsigned AudioNode::numberOfInputs() const {
  return Handler().NumberOfInputs();
}

unsigned AudioNode::numberOfOutputs() const {
  return Handler().NumberOfOutputs();
}

unsigned AudioNode::channelCount() const {
  return Handler().ChannelCount();
}

void AudioNode::setChannelCount(unsigned count,
                                ExceptionState& exception_state) {
  Handler().SetChannelCount(count, exception_state);
}

String AudioNode::channelCountMode() const {
  return Handler().GetChannelCountMode();
}

void AudioNode::setChannelCountMode(const String& mode,
                                    ExceptionState& exception_state) {
  Handler().SetChannelCountMode(mode, exception_state);
}

String AudioNode::channelInterpretation() const {
  return Handler().ChannelInterpretation();
}

void AudioNode::setChannelInterpretation(const String& interpretation,
                                         ExceptionState& exception_state) {
  Handler().SetChannelInterpretation(interpretation, exception_state);
}

const AtomicString& AudioNode::InterfaceName() const {
  return event_target_names::kAudioNode;
}

ExecutionContext* AudioNode::GetExecutionContext() const {
  return context()->GetExecutionContext();
}

void AudioNode::DidAddOutput(unsigned number_of_outputs) {
  connected_nodes_.push_back(nullptr);
  DCHECK_EQ(number_of_outputs, connected_nodes_.size());
  connected_params_.push_back(nullptr);
  DCHECK_EQ(number_of_outputs, connected_params_.size());
}

void AudioNode::SendLogMessage(const String& message) {
  WebRtcLogMessage(String::Format("[WA]AN::%s", message.Utf8().c_str()).Utf8());
}

}  // namespace blink


text:
using System;
using Messages;
using NServiceBus;
using NServiceBus.Persistence.NHibernate;

namespace Receiver
{
    public class OrderSubmittedHandler : IHandleMessages<OrderSubmitted>
    {
        public IBus Bus { get; set; }
        public NHibernateStorageContext StorageContext { get; set; }

        public void Handle(OrderSubmitted message)
        {
            Console.WriteLine("Order {0} worth {1} submitted", message.OrderId, message.Value);

            #region StoreUserData

            StorageContext.Session.Save(new Order
                                        {
                                            OrderId = message.OrderId,
                                            Value = message.Value
                                        });

            #endregion

            #region Reply

            Bus.Reply(new OrderAccepted
                      {
                          OrderId = message.OrderId,
                      });

            #endregion
        }
    }
}


text:
package com.aventstack.extentreports.model;

import java.io.Serializable;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@Getter
@Setter
@ToString(callSuper = true, includeFieldNames = true)
public final class Device extends NamedAttribute implements Serializable {
    private static final long serialVersionUID = -5585746447313067401L;

    public Device(String name) {
        super(name);
    }
}


text:
layout: redirected
sitemap: false
permalink: /comitatilocali/torino/
redirect_to:  /comitatilocali#torino
---


text:
class ProbableTournamentTree():
    """
    the probable tournament tree details the likely winners of games from the round of 16 on
    """
    MAX_LEVEL = 4

    class Node():
        def __init__(self, left, right, winner=None):
            self.left = left
            self.right = right
            self.winner = winner

        def children_winner(self):
            """
            :return: ``Team`` instance. The winner of this ``Node``'s left and right children
            """
            left_winning_prob = self.left.winner.winning_probabilities[self.right.winner.country]
            return self.left.winner if left_winning_prob >= .5 else self.right.winner

    def __init__(self, tournament):
        self.tournament = tournament
        self.groups = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
        self.group_pointer = 0
        self.group_subpointer = 0
        self.root = self.build_tree(self.Node(None, None))

    def _search_subtree(self, subtree, team):
        """
        :param subtree: ``Node`` instance, the subtree to search
        :param team: ``Team`` instance, the team to search ``subtree`` for
        :return: ``True`` if ``team`` in ``subtree``. ``False`` o/w
        """
        if subtree.winner.country == team.country:
            return True
        elif subtree.left is None or subtree.right is None:
            return False
        else:
            return self._search_subtree(subtree.left, team) or self._search_subtree(subtree.right, team)

    def build_tree(self, node, cur_level=MAX_LEVEL):
        """
        :param node: the current root of the tree being built
        :return: ``Node`` the original node fed into the method completely built into a tree
        """
        if cur_level == 0:
            node.left = None
            node.right = None

            # the leafs value should be the winner of the group pointed to by self.group_pointer
            group = self.groups[self.group_pointer % len(self.groups)]
            group_winners = self.tournament.get_group_winners(group)

            # 1st place from group should play 2nd place from sibling group
            node.winner = group_winners[self.group_subpointer]
            self.group_pointer += 1
            # make sure that we invert the order of choosing 1st place / 2nd place after traversing all groups once
            self.group_subpointer = 1 if self.group_subpointer == 0 or self.group_pointer == len(self.groups) else 0
        else:
            node.left = self.build_tree(self.Node(None, None), cur_level=cur_level - 1)
            node.right = self.build_tree(self.Node(None, None), cur_level=cur_level - 1)
            node.winner = node.children_winner()

        return node

    def get_opponent_at_stage(self, team, stage):
        """
        :param team: ``Team`` instance to get the probable opponent for
        :param stage: ``int`` the stage to get the probable opponent for ``team`` at. (Stage should always be between
        0 inclusive and 3 exclusive)
        :return: ``Team`` instance the ``team``'s likely opponent at ``stage``

        This method has two distinct paths depending on whether ``team`` is a part of the probability tree or not.
        If not, it means it's likely they won't make it out of group, so to get their likely opponent at ``stage``,
        we emulate the team in their group who came in second and find that team's opponent at ``stage``. If ``team`` is
        already in the tree, the method is more straightforward.
        """
        def _helper(node, t=None, cur_level=self.MAX_LEVEL):
            deeper_level = cur_level - 1
            if deeper_level < 0:
                return None
            elif deeper_level == stage:
                # if the next level is the one that we're looking for, then get the subtree (left or right) that the
                # team we're searching for is in and return the direct child from the opposite subtree, this is their
                # opponent
                if self._search_subtree(node.left, t):
                    return node.right.winner
                elif self._search_subtree(node.right, t):
                    return node.left.winner
                else:
                    return None
            else:
                return _helper(node.left, t=t, cur_level=deeper_level) or _helper(node.right, t=t, cur_level=deeper_level)

        group_winners = self.tournament.get_group_winners(team.group)
        return _helper(self.root, t=team if team in group_winners else group_winners[1])

    def print_tree(self):
        """
        print this tree to STDOUT
        """
        levels = {}

        def _helper(node, cur_depth=0):
            vals_at_level = levels.get(cur_depth, [])
            vals_at_level.append(node.winner.country)
            levels[cur_depth] = vals_at_level

            if node.left is None or node.right is None:
                return
            else:
                _helper(node.right, cur_depth=cur_depth + 1)
                _helper(node.left, cur_depth=cur_depth + 1)

        _helper(self.root)
        for level in levels.keys():
            print "\t".join(levels[level])
            print "\n"


text:
/// <reference path="../_references.ts" />
module ChartUpJs.Data {
    export class LegendItem {
        name: string;
        color: string;
    }
}


text:
DROP TABLE IF EXISTS `phpcms_message_group`;
CREATE TABLE `phpcms_message_group` (
  `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
  `typeid` smallint(5) unsigned NOT NULL DEFAULT '0',
  `groupid` tinyint(4) unsigned NOT NULL DEFAULT '0' COMMENT '用户组id',
  `subject` char(80) DEFAULT NULL,
  `content` text NOT NULL COMMENT '内容',
  `inputtime` int(10) unsigned DEFAULT '0',
  `status` tinyint(2) unsigned DEFAULT '1',
  PRIMARY KEY (`id`)
) TYPE=MyISAM;


text:
package com.sjc.cc.crystal.action;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PiePlot;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.general.DatasetUtilities;
import org.jfree.data.general.DefaultPieDataset;

import com.sjc.cc.base.LoginUserInfoHolder;
import com.sjc.cc.base.SessionUserAccessor;
import com.sjc.cc.base.jFreeChart.BaseChart;
import com.sjc.cc.base.service.ApplicationCacheService;
import com.sjc.cc.base.util.DateUtil;
import com.sjc.cc.base.vo.LoginUserInfo;
import com.sjc.cc.cloud.capacity.IdCpuRam;
import com.sjc.cc.cloud.capacity.service.CapacityService;
import com.sjc.cc.crystal.service.BillReportService;
import com.sjc.cc.crystal.service.ServiceImpl.BillReportServiceImpl.BillType;
import com.sjc.cc.crystal.vo.BillReportDetailVo;
import com.sjc.cc.crystal.vo.BillReportMonthVo;
import com.sjc.cc.entity.TccOrgan;
import com.sjc.cc.entity.TccProjectInfo;
import com.sjc.cc.login.action.LoginAction;
import com.sjc.cc.login.service.LoginService;
import com.sjc.cc.organ.service.OrganizationService;
import com.sjc.cc.pf.util.JsonResponseUtil;
import com.sjc.cc.project.service.ProjectInfoService;
import com.sjc.cc.service.util.MapUtils;

/**
 *
 * @author wangshuimin
 * @说明: 账单管理(部门)
 * @版本 :version 1.0
 * @add_time:May 19, 2014
 * @修改说明:
 * @update_time:
 */
public class BillReportAction extends BaseChart {

    private BillReportService billReportService;
    private OrganizationService organizationService;
    private ProjectInfoService projectInfoService;
    private String evnId = "0";
    private String depId = "0";
    private String proId = "0";
    private String type = "0";
    private String projectName;
    private String time;

    /**
     * 部门报表首页
     *
     * @return
     */
    public String pandect() {
        try {
            List<TccOrgan> organs = organizationService.getAllOrgan();
            Map<String, String> enviromentMap = billReportService
                    .getEnviromentMap();
            List<TccProjectInfo> projects = projectInfoService
                    .getProjectInfoListByOrganIdAndEvnId(depId, evnId);
            if (StringUtils.isBlank(time)) {
                time = DateUtil.dateToString(new Date(), DateUtil.MONTH_FORMAT);
            }
            List<BillReportMonthVo> list = billReportService.getAllReport(time,
                    evnId, depId, proId, false);
            Map<String, Integer> map = billReportService.getCountBill(list,
                    time);
            this.getRequest().setAttribute("enviromentMap", enviromentMap);
            this.getRequest().setAttribute("map", map);
            this.getRequest().setAttribute("organs", organs);
            this.getRequest().setAttribute("projects", projects);
            this.getRequest().setAttribute("time", time);// --
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return "pandect";
    }

    public String pandectDetail() {

        Map<String, String> enviromentMap = billReportService
                .getEnviromentMap();
        List<TccOrgan> organs = organizationService.getFirstTccOrgan();
        List<TccProjectInfo> projects = projectInfoService
                .getProjectInfoList(depId);
        if (StringUtils.isBlank(time)) {
            time = DateUtil.dateToString(new Date(), DateUtil.MONTH_FORMAT);
        }
        List<BillReportMonthVo> list = billReportService.getMonthReport(time,
                evnId, depId, proId, type);
        Map<String, Integer> map = billReportService.processMonthReport(list);
        this.getRequest().setAttribute("list", list);
        this.getRequest().setAttribute("enviromentMap", enviromentMap);
        this.getRequest().setAttribute("resultCount", map.get("count"));
        this.getRequest().setAttribute("organs", organs);
        this.getRequest().setAttribute("projects", projects);
        return "pandectDetail";
    }

    private LoginService loginService;

    public LoginService getLoginService() {
        return loginService;
    }

    public void setLoginService(LoginService loginService) {
        this.loginService = loginService;
    }

    /** 调用缓存Service */
    private ApplicationCacheService applicationCacheService;

    public ApplicationCacheService getApplicationCacheService() {
        return applicationCacheService;
    }

    public void setApplicationCacheService(
            ApplicationCacheService applicationCacheService) {
        this.applicationCacheService = applicationCacheService;
    }

    public String queryBill() {
        HttpServletRequest request = ServletActionContext.getRequest();
        LoginUserInfo loginUserInfo = LoginUserInfoHolder.getInstance()
                .getCurrentUser();
        loginUserInfo = new LoginUserInfo();
        String username = request.getParameter("username");
        String pwd = request.getParameter("pwd");
        String type = request.getParameter("type");

        loginUserInfo.setAccountNo(username);
        loginUserInfo.setAccountPassword(pwd);

        SessionUserAccessor.logoutSession(request.getSession());

        loginUserInfo.setLoginIP(request.getRemoteAddr());
        logger.debug("<<<<<<<<<<<<<<<<<<当前用户登录IP地址:"
                + loginUserInfo.getLoginIP());
        try {
            loginUserInfo = loginService.verifyUserPassword(loginUserInfo);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        SessionUserAccessor sessionUserAccessor = new SessionUserAccessor();
        sessionUserAccessor.setSessionUser(request.getSession(), loginUserInfo);
        setCloudUserIdCookie(loginUserInfo.getUserPartyId());
        loginUserInfo.setLoginTime(new Long(new Date().getTime()));

        request.getSession().setAttribute("loginUserInfo", loginUserInfo);
        if (type.equalsIgnoreCase("1")) {
            // 项目报表
            return "projectCrystal";
        }
        else if (type.equalsIgnoreCase("4")) {
            // 容量报表
            // return "capacitance";
        }
        else if (type.equalsIgnoreCase("3")) {
            // 服务器报表
            // try {
            // String flag = request.getParameter("viewFlag");
            // String viewPage = request.getParameter("viewPage");
            // if (flag == null)
            // flag = "0";
            // if (viewPage == null) {
            // viewPage = "1";
            // }
            // if (!"1".equals(flag)) {
            // flag = "0";
            // }
            // request.setAttribute("viewFlag", flag);
            // request.setAttribute("viewPage", viewPage);
            // request.setAttribute("proeject", "");
            // String status = request.getParameter("status");
            // if (!"0".equals(status)) {
            // status = "1";
            // }
            // request.setAttribute("viewStatus", status);
            // /** *********设置 最大 CPU RAM 外挂存储 ADD BY XINGBIAO********** */
            // // 最大CPU
            // Map<String, String> cpuMap = (Map<String, String>)
            // applicationCacheService
            // .getCacheList("163");
            // request.setAttribute("maxCPU", MapUtils.getMax(cpuMap));
            //
            // // 最大内存
            // Map<String, String> ramMap = (Map<String, String>)
            // applicationCacheService
            // .getCacheList("164");
            // request.setAttribute("maxRAM", MapUtils.getMax(ramMap));
            //
            // // 最大外挂存储
            // Map<String, String> plusStoreMap = (Map<String, String>)
            // applicationCacheService
            // .getCacheList("600");
            // request.setAttribute("maxPlusStore", MapUtils
            // .getMax(plusStoreMap));
            // /** *********设置 最大 CPU RAM 外挂存储 ADD BY XINGBIAO********** */
            // } catch (Exception e) {
            // e.printStackTrace();
            // }
            // return "releaseList";
        }
        else if (type.equalsIgnoreCase("2")) {
            // 资源可用报表
            try {
                ArrayList<IdCpuRam> rslist = capacityService.getLvTable();
                request.setAttribute("lvlist", rslist);
                return "cpuram";
            }
            catch (Exception e) {
                return "cpuram";
                // e.printStackTrace();
            }

        }
        return null;
    }

    private CapacityService capacityService;

    public CapacityService getCapacityService() {
        return capacityService;
    }

    public void setCapacityService(CapacityService capacityService) {
        this.capacityService = capacityService;
    }

    private void setCloudUserIdCookie(Long userId) {
        HttpServletResponse response = ServletActionContext.getResponse();
        Cookie loginInfo = new Cookie(LoginAction.COOKIE_CC_USER_ID, userId
                + "");
        loginInfo.setMaxAge(-1);
        if (logger.isDebugEnabled()) {
            logger.debug("The Cookie Cloud is :" + loginInfo + ","
                    + loginInfo.getValue());
        }
        response.addCookie(loginInfo);
    }

    public String personPandectDetail() {

        if (StringUtils.isBlank(time)) {
            time = DateUtil.dateToString(new Date(), DateUtil.MONTH_FORMAT);
        }
        LoginUserInfo loginUserInfo = LoginUserInfoHolder.getInstance()
                .getCurrentUser();
        List<BillReportMonthVo> list = billReportService.getPersonMonthReport(
                time, loginUserInfo.getUserPartyId().toString(), proId, type);
        Map<String, Integer> map = billReportService.processMonthReport(list);
        List<TccProjectInfo> projects = projectInfoService
                .getProjectInfos(loginUserInfo.getUserPartyId().toString());
        this.getRequest().setAttribute("list", list);
        this.getRequest().setAttribute("resultCount", map.get("count"));
        this.getRequest().setAttribute("projects", projects);
        return "personPandectDetail";
    }

    /**
     * 报表下载(execle)
     */
    public void downloadReport() {

        OutputStream os = null;
        try {
            os = this.getResponse().getOutputStream();
            // 设置返回数据类型
            this.getResponse().setContentType(
                    "application/octet-stream;charset=UTF-8");
            this.getResponse().setContentType(
                    "application/vnd.ms-excel;charset=UTF-8");
            // 设置返回的文件名
            String fileName = "账单报表";
            // 中文名称需要编译
            this.getResponse().setHeader(
                    "Content-Disposition",
                    "attachment; filename=\""
                            + URLEncoder.encode(fileName, "UTF-8") + "\".xls");
            // 统计总的报表
            String downType = this.getRequest().getParameter("downType");
            List<BillReportMonthVo> list = null;
            if ("person".endsWith(downType)) {
                LoginUserInfo loginUserInfo = LoginUserInfoHolder.getInstance()
                        .getCurrentUser();
                list = billReportService.getPersonMonthReport(time,
                        loginUserInfo.getUserPartyId().toString(), proId, type);
            }
            else {
                list = billReportService.getMonthReport(time, evnId, depId,
                        proId, type);
            }
            if (list != null) {
                billReportService.downloadReport(list, os);
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            try {
                if (os != null) {
                    os.close();
                }
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 本月应用系统详细报表
     *
     * @throws UnsupportedEncodingException
     */
    public String projectMonthDetail() throws UnsupportedEncodingException {

        projectName = StringUtils.isNotBlank(projectName) ? new String(
                projectName.getBytes("ISO-8859-1"), "utf-8") : null;
        List<BillReportMonthVo> list = billReportService.getMonthProjectData(
                time, evnId, depId, proId, projectName);
        if (StringUtils.isBlank(time)) {
            time = DateUtil.dateToString(new Date(), DateUtil.MONTH_FORMAT);
        }
        double sumAmout = 0;
        if (list != null && !list.isEmpty()) {
            for (BillReportMonthVo vo : list) {
                sumAmout += vo.getMonthAmount();
            }
            for (BillReportMonthVo vo : list) {
                vo.setRate((vo.getMonthAmount() / sumAmout) * 100);
            }
        }
        Map<String, String> enviromentMap = billReportService
                .getEnviromentMap();
        this.getRequest().setAttribute("list", list);
        this.getRequest().setAttribute("map", enviromentMap);
        return "projectMonthDetail";
    }

    /**
     * 应用系统消费详情饼图
     *
     * @throws Exception
     */
    public void projectMonthDetailPie() throws Exception {

        projectName = StringUtils.isNotBlank(projectName) ? new String(
                projectName.getBytes("ISO-8859-1"), "utf-8") : null;
        List<BillReportMonthVo> list = billReportService.getMonthProjectData(
                time, evnId, depId, proId, projectName);
        Map<String, Object> map = new HashMap<String, Object>();
        if (list != null && !list.isEmpty()) {
            for (BillReportMonthVo vo : list) {
                map.put(vo.getPartyFullName(), vo.getMonthAmount());
            }
        }
        processPieCommon(map);
    }

    /**
     * 部门报表饼图
     *
     * @throws Exception
     */
    public void billPie() throws Exception {

        String type = getRequest().getParameter("billType");
        if (StringUtils.isBlank(type)) {
            return;
        }
        List<BillReportMonthVo> list = billReportService.getAllReport(time,
                evnId, depId, proId, false);
        this.getRequest().setAttribute("time", time);// ---
        Map<String, Object> map = billReportService.getBillOrder(list,
                BillType.valueOf(type), depId, projectName);
        processPieCommon(map);
    }

    /**
     * 个人报表饼图
     *
     * @throws Exception
     */
    public void perSonBillPie() throws Exception {

        String type = getRequest().getParameter("billType");
        if (StringUtils.isBlank(type)) {
            return;
        }
        LoginUserInfo loginUserInfo = LoginUserInfoHolder.getInstance()
                .getCurrentUser();
        List<BillReportMonthVo> list = billReportService.getPersonAllReport(
                time, proId, loginUserInfo.getUserPartyId().toString(), false);
        Map<String, Object> map = billReportService.getBillOrder(list,
                BillType.valueOf(type), depId, projectName);
        processPieCommon(map);
    }

    private void processPieCommon(Map<String, Object> map) throws IOException {

        // 数据集
        DefaultPieDataset dataSet = new DefaultPieDataset();

        int total = 0;
        if (map != null && !map.isEmpty()) {
            Set<String> keys = map.keySet();
            for (String key : keys) {
                total += Integer.parseInt(map.get(key).toString());
                dataSet.setValue(key, Double.valueOf(map.get(key).toString()));
            }
        }

        // -------------------------------------------------创建json对象---------------------------------------------------------------------------------
        int jsonsize = dataSet.getItemCount();
        HashMap<String, Object> JSonMap = new HashMap<String, Object>();
        ArrayList<Object> dat = new ArrayList<Object>();
        for (int i = 0; i < jsonsize; i++) {
            Object[] str = new Object[2];
            str[0] = dataSet.getKey(i) + "(" + dataSet.getValue(i) + ")";
            str[1] = dataSet.getValue(i);
            dat.add(str);
        }
        JSonMap.put("title", "总消费" + total + "云币");
        JSonMap.put("data", dat);
        String JsonContent = JsonResponseUtil.changeObjectToJson(JSonMap);
        JsonResponseUtil.writeJsonString(JsonContent);

        /*
         * // 创建PieChart对象 JFreeChart chart = this.createPieChart("总消费"+
         * total+"云币", dataSet); PiePlot pieplot = (PiePlot)chart.getPlot();
         * //通过JFreeChart 对象获得 plot:PiePlot!!
         * pieplot.setNoDataMessage("没有统计数据!"); // 没有数据的时候显示的内容
         * ChartUtilities.writeChartAsJPEG(
         * this.getResponse().getOutputStream(), //输出到哪个输出流 1, //JPEG图片的质量,0~1之间
         * chart, //统计图标对象 450, //宽 300,//高 null //ChartRenderingInfo 信息 );
         * this.getResponse().getOutputStream().close();
         */
    }

    /**
     * 部门年消费折线图
     *
     * @throws Exception
     */
    public void billFold() throws Exception {
        List<BillReportMonthVo> list = billReportService.getAllReport(time,
                evnId, depId, proId, true);
        this.getRequest().setAttribute("time", time);// --
        Map<String, Integer> map = billReportService.getAllYearReport(list);
        commonYearBillFold(map);
    }

    /**
     * 个人年消费折线图
     *
     * @throws Exception
     */
    public void perSonBillFold() throws Exception {

        LoginUserInfo loginUserInfo = LoginUserInfoHolder.getInstance()
                .getCurrentUser();
        List<BillReportMonthVo> list = billReportService.getPersonAllReport(
                time, proId, loginUserInfo.getUserPartyId().toString(), true);
        Map<String, Integer> map = billReportService.getAllYearReport(list);
        commonYearBillFold(map);
    }

    /**
     * 年消费折线图公共方法
     *
     * @param map
     * @throws IOException
     */
    private void commonYearBillFold(Map<String, Integer> map)
            throws IOException {

        // 数据集
        double[][] data = new double[1][12];
        String[] rowKeys = { "年消费" };
        String[] columnKeys = new String[12];

        for (int i = 0; i < 12; i++) {
            String tmp = ((i < 9) ? "0" : "") + (i + 1);

            columnKeys[i] = tmp != null ? tmp : "";
            if (tmp != null && (map != null && !map.isEmpty()))
                data[0][i] = map.get(tmp) == null ? 0 : map.get(tmp);
        }

        CategoryDataset dataset = DatasetUtilities.createCategoryDataset(
                rowKeys, columnKeys, data);

        int jsonsize = dataset.getColumnKeys().size();
        dataset.getValue(0, 11);

        // ---------创建json对象------------------------------
        HashMap<String, Object> JSonMap = new HashMap<String, Object>();
        HashMap<String, Object> yy = new HashMap<String, Object>();
        HashMap<String, Object> xx = new HashMap<String, Object>();
        Object[] str = new Object[jsonsize];
        for (int i = 0; i < jsonsize; i++) {
            str[i] = dataset.getValue(0, i);
        }
        xx.put("categories", dataset.getColumnKeys());
        yy.put("name", "年消费");
        yy.put("data", str);
        JSonMap.put("xdata", xx);
        JSonMap.put("ydata", yy);
        String JsonContent = JsonResponseUtil.changeObjectToJson(JSonMap);
        JsonResponseUtil.writeJsonString(JsonContent);

        /*
         * JFreeChart chart = this.createShapeChart("", dataset,"", "");
         * //通过JFreeChart 对象获得 plot:PiePlot!!
         * chart.getPlot().setNoDataMessage("没有统计数据!"); // 没有数据的时候显示的内容
         * ChartUtilities.writeChartAsJPEG(
         * this.getResponse().getOutputStream(), //输出到哪个输出流 1, //JPEG图片的质量,0~1之间
         * chart, //统计图标对象 500, //宽 300,//高 null //ChartRenderingInfo 信息 );
         * this.getResponse().getOutputStream().close();
         */

    }

    /**
     * 部门月消费折线图
     *
     * @throws Exception
     */
    public void billMonthFold() throws Exception {

        List<BillReportMonthVo> list = billReportService.getMonthReport(time,
                evnId, depId, proId, type);
        Map<String, Integer> map = billReportService.processMonthReport(list);
        commonBillMonthFold(map);
    }

    /**
     * 个人月消费折线图
     *
     * @throws Exception
     */
    public void personBillMonthFold() throws Exception {

        LoginUserInfo loginUserInfo = LoginUserInfoHolder.getInstance()
                .getCurrentUser();
        List<BillReportMonthVo> list = billReportService.getPersonMonthReport(
                time, loginUserInfo.getUserPartyId().toString(), proId, type);
        Map<String, Integer> map = billReportService.processMonthReport(list);
        commonBillMonthFold(map);
    }

    private void commonBillMonthFold(Map<String, Integer> map)
            throws IOException {

        // 数据集
        double[][] data = new double[1][31];
        String[] rowKeys = { "日消费" };
        String[] columnKeys = new String[31];
        if (map != null && !map.isEmpty()) {
            for (int i = 0; i < 31; i++) {
                String tmp = ((i < 9) ? "0" : "") + (i + 1);
                columnKeys[i] = tmp;
                data[0][i] = map.get(tmp) == null ? 0 : map.get(tmp);
            }
        }
        CategoryDataset dataset = DatasetUtilities.createCategoryDataset(
                rowKeys, columnKeys, data);
        HashMap<String, Object> JSonMap = new HashMap<String, Object>();
        HashMap<String, Object> yy = new HashMap<String, Object>();
        yy.put("name", "日消费");
        yy.put("data", data[0]);
        JSonMap.put("xdata", columnKeys);
        JSonMap.put("ydata", yy);
        String JsonContent = JsonResponseUtil.changeObjectToJson(JSonMap);
        JsonResponseUtil.writeJsonString(JsonContent);

        /*
         * JFreeChart chart = this.createShapeChart("", dataset,"", "");
         * //通过JFreeChart 对象获得 plot:PiePlot!!
         * chart.getPlot().setNoDataMessage("没有统计数据!"); // 没有数据的时候显示的内容
         * ChartUtilities.writeChartAsJPEG(
         * this.getResponse().getOutputStream(), //输出到哪个输出流 1, //JPEG图片的质量,0~1之间
         * chart, //统计图标对象 800, //宽 300,//高 null //ChartRenderingInfo 信息 );
         * this.getResponse().getOutputStream().close();
         */
    }

    public String pandectPer() {

        if (StringUtils.isBlank(time)) {
            time = DateUtil.dateToString(new Date(), DateUtil.MONTH_FORMAT);
        }
        LoginUserInfo loginUserInfo = LoginUserInfoHolder.getInstance()
                .getCurrentUser();
        List<BillReportMonthVo> list = billReportService.getPersonAllReport(
                time, proId, loginUserInfo.getUserPartyId().toString(), true);
        Map<String, Integer> map = billReportService.getCountBill(list, time);
        List<TccProjectInfo> projects = projectInfoService
                .getProjectInfos(loginUserInfo.getUserPartyId().toString());
        this.getRequest().setAttribute("map", map);
        this.getRequest().setAttribute("projects", projects);
        return "personPandect";

    }

    /**
     * 资源详细页面
     *
     * @throws Exception
     */
    public String resourceData() throws Exception {

        String type = getRequest().getParameter("billType");
        if (StringUtils.isBlank(type)) {
            return "resourceData";
        }
        Map<String, Object> map = billReportService.getDisResource(time, evnId,
                depId, proId, type);
        List<BillReportDetailVo> list = ((map != null && !map.isEmpty()) ? (List<BillReportDetailVo>) map
                .get("data") : null);
        if (list != null && !list.isEmpty()) {
            Double count = Double.valueOf(map.get("countAmount").toString());
            for (BillReportDetailVo vo : list) {
                vo.setRate((vo.getAmount().doubleValue() / count.doubleValue()) * 100);
            }
        }
        this.getRequest().setAttribute("map", map);
        this.getRequest().setAttribute("billType", type);
        return "resourceData";
    }

    public String personResourceData() throws Exception {

        String type = getRequest().getParameter("billType");
        if (StringUtils.isBlank(type)) {
            return "personResourceData";
        }
        LoginUserInfo loginUserInfo = LoginUserInfoHolder.getInstance()
                .getCurrentUser();
        Map<String, Object> map = billReportService.getPersonDisResource(time,
                loginUserInfo.getUserPartyId().toString(), proId, type);
        List<BillReportDetailVo> list = ((map != null && !map.isEmpty()) ? (List<BillReportDetailVo>) map
                .get("data") : null);
        if (list != null && !list.isEmpty()) {
            Double count = Double.valueOf(map.get("countAmount").toString());
            for (BillReportDetailVo vo : list) {
                vo.setRate((vo.getAmount().doubleValue() / count.doubleValue()) * 100);
            }
        }
        this.getRequest().setAttribute("map", map);
        this.getRequest().setAttribute("billType", type);
        return "personResourceData";
    }

    /**
     * 资源消费饼图
     *
     * @throws Exception
     */
    public void resourcePie() throws Exception {

        String type = this.getRequest().getParameter("billType");
        if (StringUtils.isBlank(type)) {
            return;
        }
        Map<String, Object> map = billReportService.getDisResource(time, evnId,
                depId, proId, type);
        List<BillReportDetailVo> list = ((map != null && !map.isEmpty()) ? (List<BillReportDetailVo>) map
                .get("data") : null);

        // 数据集
        DefaultPieDataset dataSet = new DefaultPieDataset();
        if (list != null && !list.isEmpty()) {
            for (BillReportDetailVo vo : list) {
                dataSet.setValue(vo.getAppGradeName(),
                        Double.valueOf(vo.getAmount().toString()));
            }
        }
        Object[] obj = new Object[dataSet.getItemCount()];
        for (int i = 0; i < obj.length; i++) {
            Object[] obj2 = new Object[2];
            obj2[0] = "'" + dataSet.getKey(i).toString() + "'";
            obj2[1] = dataSet.getValue(i);
            obj[i] = obj2;
        }

        String JsonContent = JsonResponseUtil.changeArrayToJson(obj);
        JsonResponseUtil.writeJsonString(JsonContent);

        /*
         * // 创建PieChart对象 JFreeChart chart = this.createPieChart("", dataSet);
         * PiePlot pieplot = (PiePlot)chart.getPlot(); //通过JFreeChart 对象获得
         * plot:PiePlot!! pieplot.setNoDataMessage("没有统计数据!"); // 没有数据的时候显示的内容
         *
         * ChartUtilities.writeChartAsJPEG(
         * this.getResponse().getOutputStream(), //输出到哪个输出流 1, //JPEG图片的质量,0~1之间
         * chart, //统计图标对象 450, //宽 300,//高 null //ChartRenderingInfo 信息 );
         * this.getResponse().getOutputStream().close();
         */
    }

    public BillReportService getBillReportService() {
        return billReportService;
    }

    public void setBillReportService(BillReportService billReportService) {
        this.billReportService = billReportService;
    }

    public String getEvnId() {
        return evnId;
    }

    public void setEvnId(String evnId) {
        this.evnId = evnId;
    }

    public String getDepId() {
        return depId;
    }

    public void setDepId(String depId) {
        this.depId = depId;
    }

    public String getProId() {
        return proId;
    }

    public void setProId(String proId) {
        this.proId = proId;
    }

    public OrganizationService getOrganizationService() {
        return organizationService;
    }

    public void setOrganizationService(OrganizationService organizationService) {
        this.organizationService = organizationService;
    }

    public ProjectInfoService getProjectInfoService() {
        return projectInfoService;
    }

    public void setProjectInfoService(ProjectInfoService projectInfoService) {
        this.projectInfoService = projectInfoService;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }

    public String getProjectName() {
        return projectName;
    }

    public void setProjectName(String projectName) {
        this.projectName = projectName;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

}