<commit_before>void recTPC2007(Int_t type, const char *filename="data.root")
{

  // .x recTPC(0,"rfio:/castor/cern.ch/alice/tpc/2007/12/13/00/07000011524011.980.root")
  //
  // Set path to calibration data
  //
  // type variable = 0 - cosmic test
  //               = 1 - laser test
  //
  // Set reconstruction parameters
  ////
  gSystem->Load("/afs/cern.ch/alice/tpctest/root/HEAD/lib/libRAliEn.so");
  TGrid::Connect("alien://");
  //

  AliLog::SetClassDebugLevel("AliTPCclustererMI",2);
  AliTPCRecoParam * tpcRecoParam = 0;
  if (type==0)  tpcRecoParam = AliTPCRecoParam::GetCosmicTestParam(kTRUE);
  if (type>0)  tpcRecoParam = AliTPCRecoParam::GetLaserTestParam(kTRUE);
  tpcRecoParam->SetTimeInterval(60,1000);
  tpcRecoParam->Dump();
  AliTPCReconstructor::SetRecoParam(tpcRecoParam);
  AliTPCReconstructor::SetStreamLevel(1);
  AliMagFMaps* field = new AliMagFMaps("Maps","Maps", 2, 1., 10., 1);
  AliTracker::SetFieldMap(field,1);
  //
  //
  AliReconstruction rec;
  rec.SetDefaultStorage("alien://folder=/alice/data/2007/LHC07w/OCDB/");
  rec.SetWriteESDfriend(kTRUE);
  rec.SetInput(filename);
  rec.SetRunReconstruction("TPC");
  rec.SetEquipmentIdMap("EquipmentIdMap.data");
  //
  rec.SetOption("TPC","PedestalSubtraction OldRCUFormat");
  rec.SetFillESD("TPC");
  rec.SetFillTriggerESD(kFALSE);
  rec.SetRunVertexFinder(kFALSE);
  rec.Run();
}

<commit_msg>Changing parameters (Marian)<commit_after>void recTPC2007(Int_t type, const char *filename="data.root")
{
  //  .L $ALICE_ROOT/TPC/macros/recTPC2007.C

  // recTPC2007(0,"rfio:/castor/cern.ch/alice/data/2007/12/16/11/07000013151011.20.root")
  //recTPC2007(0,"alien:///alice/data/2007/LHC07w_TPC/000012674/raw/07000012674011.90.root")
  //  recTPC2007(0,"/data/test2007/07000012674011/07000012674011.90.root")

  //
  // Set path to calibration data
  //
  // type variable = 0 - cosmic test
  //               = 1 - laser test
  //
  // Set reconstruction parameters
  ////
  //gSystem->Load("/afs/cern.ch/alice/tpctest/root/HEAD/lib/libRAliEn.so");
  //gSystem->Load("$ROOTSYS/lib/libXrdClient.so")
  TGrid::Connect("alien://");
  //

  AliLog::SetClassDebugLevel("AliTPCclustererMI",2);
  AliTPCRecoParam * tpcRecoParam = 0;
  if (type==0)  tpcRecoParam = AliTPCRecoParam::GetCosmicTestParam(kTRUE);
  if (type>0)  tpcRecoParam = AliTPCRecoParam::GetLaserTestParam(kTRUE);
  tpcRecoParam->SetTimeInterval(60,940);
  tpcRecoParam->Dump();
  //
  //
 //  tpcRecoParam->SetMinMaxCutAbs(4.);
//   tpcRecoParam->SetMinLeftRightCutAbs(6.);
//   tpcRecoParam->SetMinUpDownCutAbs(7.);
//   tpcRecoParam->SetMinMaxCutSigma(4.);
//   tpcRecoParam->SetMinLeftRightCutSigma(6.);
//   tpcRecoParam->SetMinUpDownCutSigma(7.);
  //
  //
  AliTPCReconstructor::SetRecoParam(tpcRecoParam);
  AliTPCReconstructor::SetStreamLevel(100);
  AliMagFMaps* field = new AliMagFMaps("Maps","Maps", 2, 1., 10., 1);
  AliTracker::SetFieldMap(field,1);
  //
  //
  AliReconstruction rec;
  rec.SetDefaultStorage("alien://folder=/alice/data/2007/LHC07w/OCDB/");
  rec.SetWriteESDfriend(kTRUE);
  rec.SetInput(filename);
  rec.SetRunReconstruction("TPC");
  rec.SetEquipmentIdMap("EquipmentIdMap.data");
  //
  rec.SetOption("TPC","PedestalSubtraction OldRCUFormat");
  rec.SetFillESD("TPC");
  rec.SetFillTriggerESD(kFALSE);
  rec.SetRunVertexFinder(kFALSE);
  rec.SetCleanESD(kFALSE);
  rec.Run();
}

<|endoftext|>


<commit_before>/**********************************************************************
// @@@ START COPYRIGHT @@@
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
//
// @@@ END COPYRIGHT @@@
**********************************************************************/
/* -*-C++-*-
****************************************************************************
*
* File:         Helper functions for use by bin/clitest.cpp
* Description:  Test driver useing exe util cli interface
*
*
*
*
****************************************************************************
*/
#include "blobtest.h"

Int32 extractLengthOfLobColumn(CliGlobals *cliglob, char *lobHandle,
			       Int64 &lengthOfLob,
			       char *lobColumnName, char *tableName)
{
  Int32 retcode = 0;
  char * query = new char[4096];
  ExeCliInterface cliInterface((cliglob->currContext())->exHeap(), (Int32)SQLCHARSETCODE_UTF8, cliglob->currContext(),NULL);
  //Use lob handle to retrieve the lob length.
  char lobLengthResult[200];
  str_cpy_all(lobLengthResult," ",200);
  Int32 lobLengthResultLen = 0;
  str_sprintf(query,"extract loblength (lob '%s') LENGTH %ld ",lobHandle, lengthOfLob);
  retcode = cliInterface.executeImmediate(query,lobLengthResult,&lobLengthResultLen,FALSE);

  delete query;
  return retcode;

}

Int32 extractLobHandle(CliGlobals *cliglob, char *& lobHandle,
		       char *lobColumnName, char *tableName)
{
  Int32 retcode = 0;
  ExeCliInterface cliInterface((cliglob->currContext())->exHeap(), (Int32)SQLCHARSETCODE_UTF8, cliglob->currContext(),NULL);
  char * query = new char[4096];
  Int32 lobHandleLen = 0;
  str_sprintf(query,"select %s from %s",lobColumnName,tableName);

  retcode = cliInterface.executeImmediate(query,lobHandle,&lobHandleLen,FALSE);

  lobHandle[lobHandleLen]='\0';
  delete query;

  return retcode;

}

Int32 extractLobToBuffer(CliGlobals *cliglob, char * lobHandle, Int64 &lengthOfLob,
				char *lobColumnName, char *tableName)
{
  Int32 retcode = 0;
  ExeCliInterface cliInterface((cliglob->currContext())->exHeap(), (Int32)SQLCHARSETCODE_UTF8, cliglob->currContext(),NULL);
  // Extract lob data into a buffer.
  char * query = new char [500];

  char *lobFinalBuf = new char[lengthOfLob];
  char statusBuf[200] = {'\0'};
  Int32 statusBufLen = 0;
  Int64 lobExtractLen = 10000;
  char *lobDataBuf = new char[lobExtractLen];

  str_sprintf(query,"extract lobtobuffer(lob '%s', LOCATION %ld, SIZE %ld) ", lobHandle, (Int64)lobDataBuf, lobExtractLen);

  retcode = cliInterface.executeImmediatePrepare(query);
  short i = 0;
  while ((retcode != 100) && !(retcode<0))
    {
      retcode = cliInterface.clearExecFetchClose(NULL,NULL,statusBuf, &statusBufLen);
      if (retcode>= 0)
	{
	memcpy((char*)&(lobFinalBuf[i]),(char *)lobDataBuf,lobExtractLen);
	i += lobExtractLen;
	}
    }
  if (retcode ==100 || retcode ==0)
    {
      FILE * lobFileId = fopen("lob_output_file","w");

      int byteCount=fwrite(lobFinalBuf,sizeof(char),lengthOfLob, lobFileId);
      cout << "Writing " << byteCount << " bytes from user buffer to file lob_output_file in current directory" << endl;

      fclose(lobFileId);
    }
  str_sprintf(query,"extract lobtobuffer(lob '%s', LOCATION %ld, SIZE 0) ", lobHandle, (Int64)lobDataBuf);

  cliInterface.clearExecFetchClose(NULL,NULL,statusBuf, &statusBufLen);
  delete  lobFinalBuf;
  delete query;
  delete lobDataBuf;

  return retcode;

}

Int32 extractLobToFileInChunks(CliGlobals *cliglob,  char * lobHandle, char *filename,Int64 &lengthOfLob,
				char *lobColumnName, char *tableName)
{
  Int32 retcode = 0;
  ExeCliInterface cliInterface((cliglob->currContext())->exHeap(), (Int32)SQLCHARSETCODE_UTF8, cliglob->currContext(),NULL);
  // Extract lob data into a buffer.
  char * query = new char [500];

  char statusBuf[200] = {'\0'};
  Int32 statusBufLen = 0;
  Int64 lobExtractLen = 10000;
  char *lobDataBuf = new char[lobExtractLen];
  Int64 *inputOutputAddr = &lobExtractLen;

  str_sprintf(query,"extract lobtobuffer(lob '%s', LOCATION %ld, SIZE %ld) ", lobHandle, (Int64)lobDataBuf, lobExtractLen);

  retcode = cliInterface.executeImmediatePrepare(query);
  short i = 0;
  FILE * lobFileId = fopen(filename,"a+");
  int byteCount = 0;
  while ((retcode != 100) && !(retcode<0))
    {
      retcode = cliInterface.clearExecFetchClose(NULL,NULL,statusBuf, &statusBufLen);
      if (retcode>= 0)
	{
	  byteCount=fwrite(lobDataBuf,sizeof(char),*inputOutputAddr, lobFileId);
	 cout << "Wrote " << byteCount << " bytes to file : " << filename << endl;
	}
    }
  lobExtractLen = 0;
  str_sprintf(query,"extract lobtobuffer(lob '%s', LOCATION %ld, SIZE %ld) ", lobHandle, (Int64)lobDataBuf, lobExtractLen);
  retcode = cliInterface.executeImmediatePrepare(query);
  cliInterface.clearExecFetchClose(NULL,NULL,statusBuf, &statusBufLen);

  fclose(lobFileId);

  delete query;
  delete lobDataBuf;

  return retcode;

}

Int32 insertBufferToLob(CliGlobals *cliglob, char *tableName)
{
  Int32 retcode = 0;
  ExeCliInterface cliInterface((cliglob->currContext())->exHeap(), (Int32)SQLCHARSETCODE_UTF8, cliglob->currContext(),NULL);
  // Extract lob data into a buffer.
  char * query = new char [500];

  char statusBuf[200] = {'\0'};
  Int32 statusBufLen = 0;
  Int64 lobInsertLen = 10;
  char *lobDataBuf = new char[lobInsertLen];
  memcpy(lobDataBuf, "xxxxxyyyyy",10);
  str_sprintf(query,"insert into %s values (1, buffertolob (LOCATION %ld, SIZE %ld))", tableName,(Int64)lobDataBuf, lobInsertLen);

  retcode = cliInterface.executeImmediate(query);
  if (retcode <0)
    {
      cliInterface.executeImmediate("rollback work");
      delete query;
      delete lobDataBuf;

      return retcode;
    }

  retcode = cliInterface.executeImmediate("commit work");
  delete query;
  delete lobDataBuf;

  return retcode;

}

Int32 updateBufferToLob(CliGlobals *cliglob, char *tableName, char *columnName)
{
  Int32 retcode = 0;
  ExeCliInterface cliInterface((cliglob->currContext())->exHeap(), (Int32)SQLCHARSETCODE_UTF8, cliglob->currContext(),NULL);
  // Extract lob data into a buffer.
  char * query = new char [500];

  char statusBuf[200] = {'\0'};
  Int32 statusBufLen = 0;
  Int64 lobUpdateLen = 20;
  char *lobDataBuf = new char[lobUpdateLen];
  memcpy(lobDataBuf, "zzzzzzzzzzzzzzzzzzzz",20);
  str_sprintf(query,"update %s set %s= buffertolob(LOCATION %ld, SIZE %ld)", tableName,columnName, (Int64)lobDataBuf, lobUpdateLen);

  retcode = cliInterface.executeImmediate(query);
  if (retcode <0)
    {
      cliInterface.executeImmediate("rollback work");
      delete query;
      delete lobDataBuf;
      return retcode;
    }

  retcode = cliInterface.executeImmediate("commit work");
  delete query;
  delete lobDataBuf;

  return retcode;

}

Int32 updateAppendBufferToLob(CliGlobals *cliglob, char *tableName, char *columnName)
{
  Int32 retcode = 0;
  ExeCliInterface cliInterface((cliglob->currContext())->exHeap(), (Int32)SQLCHARSETCODE_UTF8, cliglob->currContext(),NULL);
  // Extract lob data into a buffer.
  char * query = new char [500];

  char statusBuf[200] = {'\0'};
  Int32 statusBufLen = 0;
  Int64 lobUpdateLen = 15;
  char *lobDataBuf = new char[lobUpdateLen];
  memcpy(lobDataBuf, "aaaaabbbbbccccc",15);
  str_sprintf(query,"update %s set %s=buffertolob (LOCATION %ld, SIZE %ld,append)", tableName, columnName,(Int64)lobDataBuf, lobUpdateLen);

  retcode = cliInterface.executeImmediate(query);
  if (retcode <0)
    {
      cliInterface.executeImmediate("rollback work");
      delete query;
      delete lobDataBuf;
      return retcode;
    }

  retcode = cliInterface.executeImmediate("commit work");
  delete query;
  delete lobDataBuf;

  return retcode;

}

Int32 updateBufferToLobHandle(CliGlobals *cliglob,char *handle)
{
  Int32 retcode = 0;
  ExeCliInterface cliInterface((cliglob->currContext())->exHeap(), (Int32)SQLCHARSETCODE_UTF8, cliglob->currContext(),NULL);
  // update lob data into via a buffer.
  char * query = new char [500];

  char statusBuf[200] = {'\0'};
  Int32 statusBufLen = 0;
  Int64 lobUpdateLen = 20;
  char *lobDataBuf = new char[lobUpdateLen];
  memcpy(lobDataBuf, "zzzzzzzzzzzzzzzzzzzz",20);
  str_sprintf(query,"update lob (LOB '%s' , LOCATION %ld, SIZE %ld)", handle, (Int64)lobDataBuf, lobUpdateLen);

  retcode = cliInterface.executeImmediate(query);
  if (retcode <0)
    {
      cliInterface.executeImmediate("rollback work");
      delete query;
      delete lobDataBuf;
      return retcode;
    }

  retcode = cliInterface.executeImmediate("commit work");
  delete query;
  delete lobDataBuf;

  return retcode;

}

Int32 updateAppendBufferToLobHandle(CliGlobals *cliglob,char *handle, Int64 lobUpdateLen, Int64 sourceAddress)
{
  Int32 retcode = 0;
  ExeCliInterface cliInterface((cliglob->currContext())->exHeap(), (Int32)SQLCHARSETCODE_UTF8, cliglob->currContext(),NULL);
  // update lob data into via a buffer.
  char * query = new char [500];

  char statusBuf[200] = {'\0'};
  Int32 statusBufLen = 0;
  char *lobDataBuf = new char[lobUpdateLen];
  memcpy(lobDataBuf, (char *)sourceAddress,lobUpdateLen);
  str_sprintf(query,"update lob (LOB '%s' , LOCATION %ld, SIZE %ld,append )", handle, (Int64)lobDataBuf, lobUpdateLen);

  retcode = cliInterface.executeImmediate(query);
  if (retcode <0)
    {
      cliInterface.executeImmediate("rollback work");
      delete query;
      delete lobDataBuf;
      return retcode;
    }

  retcode = cliInterface.executeImmediate("commit work");
  delete query;
  delete lobDataBuf;

  return retcode;

}

Int32 updateTruncateLobHandle(CliGlobals *cliglob,char *handle)
{
  Int32 retcode = 0;
  ExeCliInterface cliInterface((cliglob->currContext())->exHeap(), (Int32)SQLCHARSETCODE_UTF8, cliglob->currContext(),NULL);
  // update lob data into via a buffer.
  char * query = new char [500];

  char statusBuf[200] = {'\0'};
  Int32 statusBufLen = 0;
  Int64 lobUpdateLen = 20;
  char *lobDataBuf = new char[lobUpdateLen];
  memcpy(lobDataBuf, "zzzzzzzzzzzzzzzzzzzz",20);
  str_sprintf(query,"update lob (LOB '%s' , empty_blob())", handle);

  retcode = cliInterface.executeImmediate(query);
  if (retcode <0)
    {
      cliInterface.executeImmediate("rollback work");
      delete query;
      delete lobDataBuf;
      return retcode;
    }

  retcode = cliInterface.executeImmediate("commit work");
  delete query;
  delete lobDataBuf;

  return retcode;

}
<commit_msg>[TRAFODION-2754] Get statistics cores sqlci or mxosrvr at str_sprintf()<commit_after>/**********************************************************************
// @@@ START COPYRIGHT @@@
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
//
// @@@ END COPYRIGHT @@@
**********************************************************************/
/* -*-C++-*-
****************************************************************************
*
* File:         Helper functions for use by bin/clitest.cpp
* Description:  Test driver useing exe util cli interface
*
*
*
*
****************************************************************************
*/
#include "blobtest.h"

Int32 extractLengthOfLobColumn(CliGlobals *cliglob, char *lobHandle,
			       Int64 &lengthOfLob,
			       char *lobColumnName, char *tableName)
{
  Int32 retcode = 0;
  char * query = new char[4096];
  ExeCliInterface cliInterface((cliglob->currContext())->exHeap(), (Int32)SQLCHARSETCODE_UTF8, cliglob->currContext(),NULL);
  //Use lob handle to retrieve the lob length.
  char lobLengthResult[200];
  str_cpy_all(lobLengthResult," ",200);
  Int32 lobLengthResultLen = 0;
  sprintf(query,"extract loblength (lob '%s') LOCATION %lu ",lobHandle, (unsigned long)&lengthOfLob);
  retcode = cliInterface.executeImmediate(query,lobLengthResult,&lobLengthResultLen,FALSE);

  delete query;
  return retcode;

}

Int32 extractLobHandle(CliGlobals *cliglob, char *& lobHandle,
		       char *lobColumnName, char *tableName)
{
  Int32 retcode = 0;
  ExeCliInterface cliInterface((cliglob->currContext())->exHeap(), (Int32)SQLCHARSETCODE_UTF8, cliglob->currContext(),NULL);
  char * query = new char[4096];
  Int32 lobHandleLen = 0;
  sprintf(query,"select %s from %s",lobColumnName,tableName);

  retcode = cliInterface.executeImmediate(query,lobHandle,&lobHandleLen,FALSE);

  lobHandle[lobHandleLen]='\0';
  delete query;

  return retcode;

}

Int32 extractLobToBuffer(CliGlobals *cliglob, char * lobHandle, Int64 &lengthOfLob,
				char *lobColumnName, char *tableName)
{
  Int32 retcode = 0;
  ExeCliInterface cliInterface((cliglob->currContext())->exHeap(), (Int32)SQLCHARSETCODE_UTF8, cliglob->currContext(),NULL);
  // Extract lob data into a buffer.
  char * query = new char [500];

  char *lobFinalBuf = new char[lengthOfLob];
  char statusBuf[200] = {'\0'};
  Int32 statusBufLen = 0;
  Int64 lobExtractLen = 10000;
  char *lobDataBuf = new char[lobExtractLen];

  sprintf(query,"extract lobtobuffer(lob '%s', LOCATION %lu, SIZE %ld) ", lobHandle, (unsigned long)lobDataBuf, lobExtractLen);

  retcode = cliInterface.executeImmediatePrepare(query);
  short i = 0;
  while ((retcode != 100) && !(retcode<0))
    {
      retcode = cliInterface.clearExecFetchClose(NULL,NULL,statusBuf, &statusBufLen);
      if (retcode>= 0)
	{
	memcpy((char*)&(lobFinalBuf[i]),(char *)lobDataBuf,lobExtractLen);
	i += lobExtractLen;
	}
    }
  if (retcode ==100 || retcode ==0)
    {
      FILE * lobFileId = fopen("lob_output_file","w");

      int byteCount=fwrite(lobFinalBuf,sizeof(char),lengthOfLob, lobFileId);
      cout << "Writing " << byteCount << " bytes from user buffer to file lob_output_file in current directory" << endl;

      fclose(lobFileId);
    }
  sprintf(query,"extract lobtobuffer(lob '%s', LOCATION %lu, SIZE 0) ", lobHandle, (unsigned long)lobDataBuf);

  cliInterface.clearExecFetchClose(NULL,NULL,statusBuf, &statusBufLen);
  delete  lobFinalBuf;
  delete query;
  delete lobDataBuf;

  return retcode;

}

Int32 extractLobToFileInChunks(CliGlobals *cliglob,  char * lobHandle, char *filename,Int64 &lengthOfLob,
				char *lobColumnName, char *tableName)
{
  Int32 retcode = 0;
  ExeCliInterface cliInterface((cliglob->currContext())->exHeap(), (Int32)SQLCHARSETCODE_UTF8, cliglob->currContext(),NULL);
  // Extract lob data into a buffer.
  char * query = new char [500];

  char statusBuf[200] = {'\0'};
  Int32 statusBufLen = 0;
  Int64 lobExtractLen = 10000;
  char *lobDataBuf = new char[lobExtractLen];
  Int64 *inputOutputAddr = &lobExtractLen;

  sprintf(query,"extract lobtobuffer(lob '%s', LOCATION %lu, SIZE %lu) ", lobHandle, (unsigned long)lobDataBuf, (unsigned long)inputOutputAddr);

  retcode = cliInterface.executeImmediatePrepare(query);
  short i = 0;
  FILE * lobFileId = fopen(filename,"a+");
  int byteCount = 0;
  while ((retcode != 100) && !(retcode<0))
    {
      retcode = cliInterface.clearExecFetchClose(NULL,NULL,statusBuf, &statusBufLen);
      if (retcode>= 0)
	{
	  byteCount=fwrite(lobDataBuf,sizeof(char),*inputOutputAddr, lobFileId);
	 cout << "Wrote " << byteCount << " bytes to file : " << filename << endl;
	}
    }
  lobExtractLen = 0;
  sprintf(query,"extract lobtobuffer(lob '%s', LOCATION %lu, SIZE %ld) ", lobHandle, (unsigned long)lobDataBuf, (unsigned long)inputOutputAddr);
  retcode = cliInterface.executeImmediatePrepare(query);
  cliInterface.clearExecFetchClose(NULL,NULL,statusBuf, &statusBufLen);

  fclose(lobFileId);

  delete query;
  delete lobDataBuf;

  return retcode;

}

Int32 insertBufferToLob(CliGlobals *cliglob, char *tableName)
{
  Int32 retcode = 0;
  ExeCliInterface cliInterface((cliglob->currContext())->exHeap(), (Int32)SQLCHARSETCODE_UTF8, cliglob->currContext(),NULL);
  // Extract lob data into a buffer.
  char * query = new char [500];

  char statusBuf[200] = {'\0'};
  Int32 statusBufLen = 0;
  Int64 lobInsertLen = 10;
  char *lobDataBuf = new char[lobInsertLen];
  memcpy(lobDataBuf, "xxxxxyyyyy",10);
  sprintf(query,"insert into %s values (1, buffertolob (LOCATION %lu, SIZE %ld))", tableName, (unsigned long)lobDataBuf, lobInsertLen);

  retcode = cliInterface.executeImmediate(query);
  if (retcode <0)
    {
      cliInterface.executeImmediate("rollback work");
      delete query;
      delete lobDataBuf;

      return retcode;
    }

  retcode = cliInterface.executeImmediate("commit work");
  delete query;
  delete lobDataBuf;

  return retcode;

}

Int32 updateBufferToLob(CliGlobals *cliglob, char *tableName, char *columnName)
{
  Int32 retcode = 0;
  ExeCliInterface cliInterface((cliglob->currContext())->exHeap(), (Int32)SQLCHARSETCODE_UTF8, cliglob->currContext(),NULL);
  // Extract lob data into a buffer.
  char * query = new char [500];

  char statusBuf[200] = {'\0'};
  Int32 statusBufLen = 0;
  Int64 lobUpdateLen = 20;
  char *lobDataBuf = new char[lobUpdateLen];
  memcpy(lobDataBuf, "zzzzzzzzzzzzzzzzzzzz",20);
  sprintf(query,"update %s set %s= buffertolob(LOCATION %lu, SIZE %ld)", tableName,columnName, (unsigned long)lobDataBuf, lobUpdateLen);

  retcode = cliInterface.executeImmediate(query);
  if (retcode <0)
    {
      cliInterface.executeImmediate("rollback work");
      delete query;
      delete lobDataBuf;
      return retcode;
    }

  retcode = cliInterface.executeImmediate("commit work");
  delete query;
  delete lobDataBuf;

  return retcode;

}

Int32 updateAppendBufferToLob(CliGlobals *cliglob, char *tableName, char *columnName)
{
  Int32 retcode = 0;
  ExeCliInterface cliInterface((cliglob->currContext())->exHeap(), (Int32)SQLCHARSETCODE_UTF8, cliglob->currContext(),NULL);
  // Extract lob data into a buffer.
  char * query = new char [500];

  char statusBuf[200] = {'\0'};
  Int32 statusBufLen = 0;
  Int64 lobUpdateLen = 15;
  char *lobDataBuf = new char[lobUpdateLen];
  memcpy(lobDataBuf, "aaaaabbbbbccccc",15);
  sprintf(query,"update %s set %s=buffertolob (LOCATION %lu, SIZE %ld,append)", tableName, columnName, (unsigned long)lobDataBuf, lobUpdateLen);

  retcode = cliInterface.executeImmediate(query);
  if (retcode <0)
    {
      cliInterface.executeImmediate("rollback work");
      delete query;
      delete lobDataBuf;
      return retcode;
    }

  retcode = cliInterface.executeImmediate("commit work");
  delete query;
  delete lobDataBuf;

  return retcode;

}

Int32 updateBufferToLobHandle(CliGlobals *cliglob,char *handle)
{
  Int32 retcode = 0;
  ExeCliInterface cliInterface((cliglob->currContext())->exHeap(), (Int32)SQLCHARSETCODE_UTF8, cliglob->currContext(),NULL);
  // update lob data into via a buffer.
  char * query = new char [500];

  char statusBuf[200] = {'\0'};
  Int32 statusBufLen = 0;
  Int64 lobUpdateLen = 20;
  char *lobDataBuf = new char[lobUpdateLen];
  memcpy(lobDataBuf, "zzzzzzzzzzzzzzzzzzzz",20);
  sprintf(query,"update lob (LOB '%s' , LOCATION %lu, SIZE %ld)", handle, (unsigned long)lobDataBuf, lobUpdateLen);

  retcode = cliInterface.executeImmediate(query);
  if (retcode <0)
    {
      cliInterface.executeImmediate("rollback work");
      delete query;
      delete lobDataBuf;
      return retcode;
    }

  retcode = cliInterface.executeImmediate("commit work");
  delete query;
  delete lobDataBuf;

  return retcode;

}

Int32 updateAppendBufferToLobHandle(CliGlobals *cliglob,char *handle, Int64 lobUpdateLen, Int64 sourceAddress)
{
  Int32 retcode = 0;
  ExeCliInterface cliInterface((cliglob->currContext())->exHeap(), (Int32)SQLCHARSETCODE_UTF8, cliglob->currContext(),NULL);
  // update lob data into via a buffer.
  char * query = new char [500];

  char statusBuf[200] = {'\0'};
  Int32 statusBufLen = 0;
  char *lobDataBuf = new char[lobUpdateLen];
  memcpy(lobDataBuf, (char *)sourceAddress,lobUpdateLen);
  sprintf(query,"update lob (LOB '%s' , LOCATION %lu, SIZE %ld,append )", handle, (unsigned long)lobDataBuf, lobUpdateLen);

  retcode = cliInterface.executeImmediate(query);
  if (retcode <0)
    {
      cliInterface.executeImmediate("rollback work");
      delete query;
      delete lobDataBuf;
      return retcode;
    }

  retcode = cliInterface.executeImmediate("commit work");
  delete query;
  delete lobDataBuf;

  return retcode;

}

Int32 updateTruncateLobHandle(CliGlobals *cliglob,char *handle)
{
  Int32 retcode = 0;
  ExeCliInterface cliInterface((cliglob->currContext())->exHeap(), (Int32)SQLCHARSETCODE_UTF8, cliglob->currContext(),NULL);
  // update lob data into via a buffer.
  char * query = new char [500];

  char statusBuf[200] = {'\0'};
  Int32 statusBufLen = 0;
  Int64 lobUpdateLen = 20;
  char *lobDataBuf = new char[lobUpdateLen];
  memcpy(lobDataBuf, "zzzzzzzzzzzzzzzzzzzz",20);
  sprintf(query,"update lob (LOB '%s' , empty_blob())", handle);

  retcode = cliInterface.executeImmediate(query);
  if (retcode <0)
    {
      cliInterface.executeImmediate("rollback work");
      delete query;
      delete lobDataBuf;
      return retcode;
    }

  retcode = cliInterface.executeImmediate("commit work");
  delete query;
  delete lobDataBuf;

  return retcode;

}
<|endoftext|>


<commit_before>#include "GL.h"
#include "PrimitiveRenderer.h"
#include <VBO.h>

#include "../system/StringUtils.h"

#include <iostream>

using namespace std;

PrimitiveRenderer::PrimitiveRenderer() {

}

static set<int> readCompressedFormats() {
  set<int> r;
  GLint num_compressed_format;
  glGetIntegerv(GL_NUM_COMPRESSED_TEXTURE_FORMATS, &num_compressed_format);
  if (num_compressed_format > 0) {
    GLint * compressed_format = new GLint[num_compressed_format * sizeof(GLint)];
    glGetIntegerv(GL_COMPRESSED_TEXTURE_FORMATS, compressed_format);
    for (unsigned int i = 0; i < num_compressed_format; i++) {
      r.insert(compressed_format[i]);
    }
    delete[] compressed_format;
  }
  return r;
}

static set<string> readExtensions() {
  set<string> r;
  GLint numExtensions;
  glGetIntegerv(GL_NUM_EXTENSIONS, &numExtensions);
  if (numExtensions > 0) {
    for (int i = 0; i < numExtensions; i++) {
      const GLubyte * e = glGetStringi(GL_EXTENSIONS, i);
      r.insert((const char *)e);
    }
  }
  return r;
}

void
PrimitiveRenderer::initializeBase() {
#ifdef _WIN32
  GLenum err = glewInit();
  if (GLEW_OK != err) {
    /* Problem: glewInit failed, something is seriously wrong. */
    fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
    assert(0);
  }
  fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION));
#endif

  glPolygonOffset(1, 2);
  glClearColor(0.98f, 0.98f, 0.98f, 1.0f);
  glActiveTexture(GL_TEXTURE0);

  glStencilFuncSeparate(GL_FRONT, GL_EQUAL, 0, 0xff);
  glStencilFuncSeparate(GL_BACK, GL_NEVER, 0, 0xff);
  glStencilOpSeparate(GL_FRONT, GL_DECR_WRAP, GL_KEEP, GL_KEEP);
  glStencilOpSeparate(GL_BACK, GL_INCR_WRAP, GL_KEEP, GL_KEEP);

#if 0
#if 1
  static const GLfloat light0_pos[4]   = { -50.0f, 50.0f, 0.0f, 0.0f };
#else
  static const GLfloat light0_pos[4]   = { 0.0f, 0.0f, +50.0f, 0.0f };
#endif

  // white light
  static const GLfloat light0_color[4] = { 0.6f, 0.6f, 0.6f, 1.0f };
  static const GLfloat light1_pos[4]   = {  50.0f, 50.0f, 0.0f, 0.0f };

  // cold blue light
  static const GLfloat light1_color[4] = { 0.4f, 0.4f, 1.0f, 1.0f };
#endif

#if 0
  /* light */
  glLightfv(GL_LIGHT0, GL_POSITION, light0_pos);
  glLightfv(GL_LIGHT0, GL_DIFFUSE,  light0_color);
  glEnable(GL_LIGHT0);
  glLightfv(GL_LIGHT1, GL_POSITION, light1_pos);
  glLightfv(GL_LIGHT1, GL_DIFFUSE,  light1_color);
  glEnable(GL_LIGHT1);
#endif

  set<int> compressed_formats = readCompressedFormats();
  set<string> extensions = readExtensions();

  // GL_ARB_ES2_compatibility
  // GL_ARB_ES3_compatibility
  // GL_ARB_texture_storage
  // GL_ARB_compressed_texture_pixel_storage
  // GL_EXT_abgr, GL_EXT_bgra

  has_dxt1 = extensions.count("GL_EXT_texture_compression_dxt1");
  has_etc1 = extensions.count("OES_compressed_ETC1_RGB8_texture");
  has_rgtc = extensions.count("GL_ARB_texture_compression_rgtc") || extensions.count("GL_EXT_texture_compression_rgtc");

  // GL_IMG_texture_compression_pvrtc"
  // GL_AMD_compressed_ATC_texture / GL_ATI_texture_compression_atitc
  // GL_OES_texture_compression_S3TC / GL_EXT_texture_compression_s3tc

  // EXT_texture_rg : RED and RG modes

  const char * version_str = (const char *)glGetString(GL_VERSION);
  if (version_str) {
    // OpenGL ES 3.0 Apple A7 GPU - 75.9.3
    // 3.0 Mesa 11.0.2
    cerr << "got version: " << version_str << endl;
    vector<string> parts = StringUtils::split(version_str);
    if (parts.size() >= 3 && parts[0] == "OpenGL" && parts[1] == "ES") {
      const string & es_version = parts[2];
      cerr << "got OpenGL ES: " << es_version << endl;
      if (es_version == "3.0") {
	cerr << "has etc1" << endl;
	has_etc1 = true;
	is_es3 = true;
      }
      has_rgb565 = true;
    } else if (parts.size() >= 2 && parts[1] == "Mesa") {

    } else {
      assert(0);
    }
  }

  int ii;
  glGetIntegerv(GL_MAX_TEXTURE_SIZE, &ii);
  max_texture_size = ii;
  cerr << "Maximum texture size is " << max_texture_size << endl;

  // MAX_VERTEX_TEXTURE_IMAGE_UNITS => how many textures a vertex shader can read
}

void
PrimitiveRenderer::blend(bool t) {
  if (t != blend_enabled) {
    blend_enabled = t;
    if (t) glEnable(GL_BLEND);
    else glDisable(GL_BLEND);
  }
}

void
PrimitiveRenderer::stencilTest(bool t) {
  if (t != stencil_test_enabled) {
    stencil_test_enabled = t;
    if (t) glEnable(GL_STENCIL_TEST);
    else glDisable(GL_STENCIL_TEST);
  }
}

void
PrimitiveRenderer::stencilMask(int m) {
  if (m != current_stencil_mask) {
    current_stencil_mask = m;
    glStencilMask(m);
  }
}

void
PrimitiveRenderer::depthTest(bool t) {
  if (t != depth_test_enabled) {
    depth_test_enabled = t;
    if (t) glEnable(GL_DEPTH_TEST);
    else glDisable(GL_DEPTH_TEST);
  }
}

void
PrimitiveRenderer::depthMask(bool m) {
  if (m != current_depth_mask) {
    current_depth_mask = m;
    glDepthMask(m ? GL_TRUE : GL_FALSE);
  }
}

void
PrimitiveRenderer::cullFace(bool t) {
  if (t != cull_face_enabled) {
    cull_face_enabled = t;
    if (t) glEnable(GL_CULL_FACE);
    else glDisable(GL_CULL_FACE);
  }
}

void
PrimitiveRenderer::setLineWidth(float w) {
  if (w != current_line_width) {
    current_line_width = w;
    glLineWidth(w);
  }
}

void
PrimitiveRenderer::bind(const canvas::TextureRef & texture) {
  int id = texture.getTextureId();
  if (!id) {
    cerr << "trying to bind zero tex" << endl;
    assert(0);
  } else if (id != current_texture_2d) {
    current_texture_2d = id;
    glBindTexture(GL_TEXTURE_2D, id);
  }
}

void
PrimitiveRenderer::bind(const VBO & vbo) {
  int a = vbo.getVertexArrayId();
  if (!a) {
    cerr << "trying to bind zero vao" << endl;
    assert(0);
  } else if (a != current_vertex_array) {
    current_vertex_array = a;
    glBindVertexArray(a);

    // glBindBuffer(GL_ARRAY_BUFFER, vbo.getVertexBufferId());
    // glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo.getIndexBufferId());
  }
}

void
PrimitiveRenderer::use(const gpufw::shader_program & program) {
  int id = program.getProgramObjectId();
  if (!id) {
    assert(0);
  } else if (id != current_program) {
    current_program = id;
    glUseProgram(id);
  }
}

void
PrimitiveRenderer::clear(int clear_bits) {
  int gl_bits = 0;
  if (clear_bits & COLOR_BUFFER_BIT) {
    colorMask(true, true, true, true);
    gl_bits |= GL_COLOR_BUFFER_BIT;
  }
  if (clear_bits & DEPTH_BUFFER_BIT || clear_bits & DEPTH_STENCIL_BUFFER_BIT) {
    depthMask(true);
    gl_bits |= GL_DEPTH_BUFFER_BIT;
  }
  if (clear_bits & STENCIL_BUFFER_BIT || clear_bits & DEPTH_STENCIL_BUFFER_BIT) {
    stencilMask(0xff);
    gl_bits |= GL_STENCIL_BUFFER_BIT;
  }
  if (gl_bits) {
    glClear(gl_bits);
  }
}

void
PrimitiveRenderer::colorMask(bool r, bool g, bool b, bool a) {
  if (r != current_red_mask ||
      g != current_green_mask ||
      b != current_blue_mask ||
      a != current_alpha_mask) {
    current_red_mask = r;
    current_green_mask = g;
    current_blue_mask = b;
    current_alpha_mask = a;
    glColorMask( r ? GL_TRUE : GL_FALSE,
		 g ? GL_TRUE : GL_FALSE,
		 b ? GL_TRUE : GL_FALSE,
		 a ? GL_TRUE : GL_FALSE
		 );
  }
}

void
PrimitiveRenderer::setCompositionMode(CompositionMode mode) {
  if (mode != current_composition_mode) {
    current_composition_mode = mode;
    switch (mode) {
    case COPY:
      glBlendFunc(GL_ONE, GL_ZERO);
      break;
    case NORMAL:
      glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
      break;
    case MULTIPLY:
      glBlendFunc(GL_ZERO, GL_SRC_COLOR);
      break;
    }
  }
}

void
PrimitiveRenderer::viewport(unsigned int x, unsigned int y, unsigned int w, unsigned int h) {
  if (w != current_display_size.x || h != current_display_size.y) {
    current_display_size = glm::ivec2(w, h);
    cerr << "updating viewport\n";
    glViewport(0, 0, (unsigned int)(w * display_scale), (unsigned int)(h * display_scale));
  }
}

void
PrimitiveRenderer::pushGroupMarker(const char * name) {
#ifdef GL_ES
  glPushGroupMarkerEXT(0, name);
#endif
}

void
PrimitiveRenderer::popGroupMarker() {
#ifdef GL_ES
  glPopGroupMarkerEXT();
#endif
}

void
PrimitiveRenderer::invalidateFramebuffer(int bits) {
  int n = 0;
  GLenum v[4];
  if (bits & STENCIL_BUFFER_BIT) {
    v[n++] = GL_STENCIL_ATTACHMENT;
  }
  if (bits & DEPTH_BUFFER_BIT) {
    v[n++] = GL_DEPTH_ATTACHMENT;
  }
  if (n) {
    if (is_es3) {
      glInvalidateFramebuffer(GL_FRAMEBUFFER, n, &v[0]);
    } else {
#ifdef GL_ES
      // glBindFramebuffer(GL_FRAMEBUFFER, current_framebuffer);
      // glDiscardFramebufferEXT(GL_FRAMEBUFFER, n, &v[0]);
#endif
    }
  }
}
<commit_msg>add RGB565 for Mesa, assert that RGB565 is available<commit_after>#include "GL.h"
#include "PrimitiveRenderer.h"
#include <VBO.h>

#include "../system/StringUtils.h"

#include <iostream>

using namespace std;

PrimitiveRenderer::PrimitiveRenderer() {

}

static set<int> readCompressedFormats() {
  set<int> r;
  GLint num_compressed_format;
  glGetIntegerv(GL_NUM_COMPRESSED_TEXTURE_FORMATS, &num_compressed_format);
  if (num_compressed_format > 0) {
    GLint * compressed_format = new GLint[num_compressed_format * sizeof(GLint)];
    glGetIntegerv(GL_COMPRESSED_TEXTURE_FORMATS, compressed_format);
    for (unsigned int i = 0; i < num_compressed_format; i++) {
      r.insert(compressed_format[i]);
    }
    delete[] compressed_format;
  }
  return r;
}

static set<string> readExtensions() {
  set<string> r;
  GLint numExtensions;
  glGetIntegerv(GL_NUM_EXTENSIONS, &numExtensions);
  if (numExtensions > 0) {
    for (int i = 0; i < numExtensions; i++) {
      const GLubyte * e = glGetStringi(GL_EXTENSIONS, i);
      r.insert((const char *)e);
    }
  }
  return r;
}

void
PrimitiveRenderer::initializeBase() {
#ifdef _WIN32
  GLenum err = glewInit();
  if (GLEW_OK != err) {
    /* Problem: glewInit failed, something is seriously wrong. */
    fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
    assert(0);
  }
  fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION));
#endif

  glPolygonOffset(1, 2);
  glClearColor(0.98f, 0.98f, 0.98f, 1.0f);
  glActiveTexture(GL_TEXTURE0);

  glStencilFuncSeparate(GL_FRONT, GL_EQUAL, 0, 0xff);
  glStencilFuncSeparate(GL_BACK, GL_NEVER, 0, 0xff);
  glStencilOpSeparate(GL_FRONT, GL_DECR_WRAP, GL_KEEP, GL_KEEP);
  glStencilOpSeparate(GL_BACK, GL_INCR_WRAP, GL_KEEP, GL_KEEP);

#if 0
#if 1
  static const GLfloat light0_pos[4]   = { -50.0f, 50.0f, 0.0f, 0.0f };
#else
  static const GLfloat light0_pos[4]   = { 0.0f, 0.0f, +50.0f, 0.0f };
#endif

  // white light
  static const GLfloat light0_color[4] = { 0.6f, 0.6f, 0.6f, 1.0f };
  static const GLfloat light1_pos[4]   = {  50.0f, 50.0f, 0.0f, 0.0f };

  // cold blue light
  static const GLfloat light1_color[4] = { 0.4f, 0.4f, 1.0f, 1.0f };
#endif

#if 0
  /* light */
  glLightfv(GL_LIGHT0, GL_POSITION, light0_pos);
  glLightfv(GL_LIGHT0, GL_DIFFUSE,  light0_color);
  glEnable(GL_LIGHT0);
  glLightfv(GL_LIGHT1, GL_POSITION, light1_pos);
  glLightfv(GL_LIGHT1, GL_DIFFUSE,  light1_color);
  glEnable(GL_LIGHT1);
#endif

  set<int> compressed_formats = readCompressedFormats();
  set<string> extensions = readExtensions();

  // GL_ARB_ES2_compatibility
  // GL_ARB_ES3_compatibility
  // GL_ARB_texture_storage
  // GL_ARB_compressed_texture_pixel_storage
  // GL_EXT_abgr, GL_EXT_bgra

  has_dxt1 = extensions.count("GL_EXT_texture_compression_dxt1");
  has_etc1 = extensions.count("OES_compressed_ETC1_RGB8_texture");
  has_rgtc = extensions.count("GL_ARB_texture_compression_rgtc") || extensions.count("GL_EXT_texture_compression_rgtc");

  // GL_IMG_texture_compression_pvrtc"
  // GL_AMD_compressed_ATC_texture / GL_ATI_texture_compression_atitc
  // GL_OES_texture_compression_S3TC / GL_EXT_texture_compression_s3tc

  // EXT_texture_rg : RED and RG modes

  const char * version_str = (const char *)glGetString(GL_VERSION);
  if (version_str) {
    // OpenGL ES 3.0 Apple A7 GPU - 75.9.3
    // 3.0 Mesa 11.0.2
    cerr << "got version: " << version_str << endl;
    vector<string> parts = StringUtils::split(version_str);
    if (parts.size() >= 3 && parts[0] == "OpenGL" && parts[1] == "ES") {
      const string & es_version = parts[2];
      cerr << "got OpenGL ES: " << es_version << endl;
      if (es_version == "3.0") {
	cerr << "has etc1" << endl;
	has_etc1 = true;
	is_es3 = true;
      }
      has_rgb565 = true;
    } else if (parts.size() >= 2 && parts[1] == "Mesa") {
      has_rgb565 = true;
    } else {
      assert(0);
    }
  }

  assert(has_rgb565);

  int ii;
  glGetIntegerv(GL_MAX_TEXTURE_SIZE, &ii);
  max_texture_size = ii;
  cerr << "Maximum texture size is " << max_texture_size << endl;

  // MAX_VERTEX_TEXTURE_IMAGE_UNITS => how many textures a vertex shader can read
}

void
PrimitiveRenderer::blend(bool t) {
  if (t != blend_enabled) {
    blend_enabled = t;
    if (t) glEnable(GL_BLEND);
    else glDisable(GL_BLEND);
  }
}

void
PrimitiveRenderer::stencilTest(bool t) {
  if (t != stencil_test_enabled) {
    stencil_test_enabled = t;
    if (t) glEnable(GL_STENCIL_TEST);
    else glDisable(GL_STENCIL_TEST);
  }
}

void
PrimitiveRenderer::stencilMask(int m) {
  if (m != current_stencil_mask) {
    current_stencil_mask = m;
    glStencilMask(m);
  }
}

void
PrimitiveRenderer::depthTest(bool t) {
  if (t != depth_test_enabled) {
    depth_test_enabled = t;
    if (t) glEnable(GL_DEPTH_TEST);
    else glDisable(GL_DEPTH_TEST);
  }
}

void
PrimitiveRenderer::depthMask(bool m) {
  if (m != current_depth_mask) {
    current_depth_mask = m;
    glDepthMask(m ? GL_TRUE : GL_FALSE);
  }
}

void
PrimitiveRenderer::cullFace(bool t) {
  if (t != cull_face_enabled) {
    cull_face_enabled = t;
    if (t) glEnable(GL_CULL_FACE);
    else glDisable(GL_CULL_FACE);
  }
}

void
PrimitiveRenderer::setLineWidth(float w) {
  if (w != current_line_width) {
    current_line_width = w;
    glLineWidth(w);
  }
}

void
PrimitiveRenderer::bind(const canvas::TextureRef & texture) {
  int id = texture.getTextureId();
  if (!id) {
    cerr << "trying to bind zero tex" << endl;
    assert(0);
  } else if (id != current_texture_2d) {
    current_texture_2d = id;
    glBindTexture(GL_TEXTURE_2D, id);
  }
}

void
PrimitiveRenderer::bind(const VBO & vbo) {
  int a = vbo.getVertexArrayId();
  if (!a) {
    cerr << "trying to bind zero vao" << endl;
    assert(0);
  } else if (a != current_vertex_array) {
    current_vertex_array = a;
    glBindVertexArray(a);

    // glBindBuffer(GL_ARRAY_BUFFER, vbo.getVertexBufferId());
    // glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo.getIndexBufferId());
  }
}

void
PrimitiveRenderer::use(const gpufw::shader_program & program) {
  int id = program.getProgramObjectId();
  if (!id) {
    assert(0);
  } else if (id != current_program) {
    current_program = id;
    glUseProgram(id);
  }
}

void
PrimitiveRenderer::clear(int clear_bits) {
  int gl_bits = 0;
  if (clear_bits & COLOR_BUFFER_BIT) {
    colorMask(true, true, true, true);
    gl_bits |= GL_COLOR_BUFFER_BIT;
  }
  if (clear_bits & DEPTH_BUFFER_BIT || clear_bits & DEPTH_STENCIL_BUFFER_BIT) {
    depthMask(true);
    gl_bits |= GL_DEPTH_BUFFER_BIT;
  }
  if (clear_bits & STENCIL_BUFFER_BIT || clear_bits & DEPTH_STENCIL_BUFFER_BIT) {
    stencilMask(0xff);
    gl_bits |= GL_STENCIL_BUFFER_BIT;
  }
  if (gl_bits) {
    glClear(gl_bits);
  }
}

void
PrimitiveRenderer::colorMask(bool r, bool g, bool b, bool a) {
  if (r != current_red_mask ||
      g != current_green_mask ||
      b != current_blue_mask ||
      a != current_alpha_mask) {
    current_red_mask = r;
    current_green_mask = g;
    current_blue_mask = b;
    current_alpha_mask = a;
    glColorMask( r ? GL_TRUE : GL_FALSE,
		 g ? GL_TRUE : GL_FALSE,
		 b ? GL_TRUE : GL_FALSE,
		 a ? GL_TRUE : GL_FALSE
		 );
  }
}

void
PrimitiveRenderer::setCompositionMode(CompositionMode mode) {
  if (mode != current_composition_mode) {
    current_composition_mode = mode;
    switch (mode) {
    case COPY:
      glBlendFunc(GL_ONE, GL_ZERO);
      break;
    case NORMAL:
      glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
      break;
    case MULTIPLY:
      glBlendFunc(GL_ZERO, GL_SRC_COLOR);
      break;
    }
  }
}

void
PrimitiveRenderer::viewport(unsigned int x, unsigned int y, unsigned int w, unsigned int h) {
  if (w != current_display_size.x || h != current_display_size.y) {
    current_display_size = glm::ivec2(w, h);
    cerr << "updating viewport\n";
    glViewport(0, 0, (unsigned int)(w * display_scale), (unsigned int)(h * display_scale));
  }
}

void
PrimitiveRenderer::pushGroupMarker(const char * name) {
#ifdef GL_ES
  glPushGroupMarkerEXT(0, name);
#endif
}

void
PrimitiveRenderer::popGroupMarker() {
#ifdef GL_ES
  glPopGroupMarkerEXT();
#endif
}

void
PrimitiveRenderer::invalidateFramebuffer(int bits) {
  int n = 0;
  GLenum v[4];
  if (bits & STENCIL_BUFFER_BIT) {
    v[n++] = GL_STENCIL_ATTACHMENT;
  }
  if (bits & DEPTH_BUFFER_BIT) {
    v[n++] = GL_DEPTH_ATTACHMENT;
  }
  if (n) {
    if (is_es3) {
      glInvalidateFramebuffer(GL_FRAMEBUFFER, n, &v[0]);
    } else {
#ifdef GL_ES
      // glBindFramebuffer(GL_FRAMEBUFFER, current_framebuffer);
      // glDiscardFramebufferEXT(GL_FRAMEBUFFER, n, &v[0]);
#endif
    }
  }
}
<|endoftext|>


<commit_before>#include "inbuilt.h"

#include <cstdio>
#include <cstdlib>
#include <cstring>

static const char pushya[] = R"(:code (pushya)
    dex
    sta LSB,x
    sty MSB,x
+   rts ;code)";

static const char oneplus[] = R"(:code 1+
    inc LSB,x
    bne +
    inc MSB,x
+   rts ;code)";

static const char oneminus[] = R"(:code 1-
    lda LSB, x
    bne +
    dec MSB, x
+   dec LSB, x
    rts ;code)";

static const char plus[] = R"(:code +
    lda LSB, x
    clc
    adc LSB + 1, x
    sta LSB + 1, x

    lda MSB, x
    adc MSB + 1, x
    sta MSB + 1, x

    inx
    rts ;code)";

static const char minus[] = R"(:code -
    lda LSB + 1, x
    sec
    sbc LSB, x
    sta LSB + 1, x
    lda MSB + 1, x
    sbc MSB, x
    sta MSB + 1, x
    inx
    rts ;code)";

static const char twoplus[] = R"(: 2+ 1+ 1+ ;)";

static const char cfetch[] = R"(:code c@
    lda LSB,x
    sta + + 1
    lda MSB,x
    sta + + 2
+   lda $cafe
    sta LSB,x
    lda #0
    sta MSB,x
    rts ;code)";

static const char cstore[] = R"(:code c!
    lda LSB,x
    sta + + 1
    lda MSB,x
    sta + + 2
    lda LSB+1,x
+   sta $1234
    inx
    inx
    rts ;code)";

static const char swap[] = R"(:code swap
    ldy MSB, x
    lda MSB + 1, x
    sta MSB, x
    sty MSB + 1, x

    ldy LSB, x
    lda LSB + 1, x
    sta LSB, x
    sty LSB + 1, x
    rts ;code)";

static const char lit[] = R"(:code (lit)
    dex
    pla
    sta W
    pla
    sta W + 1
    ldy #1
    lda (W), y
    sta LSB, x
    iny
    lda (W), y
    sta MSB, x
    lda W
    clc
    adc #3
    sta + + 1
    lda W + 1
    adc #0
    sta + + 2
+   jmp $1234 ;code)";

static const char rot[] = R"(:code rot
    ldy MSB+2, x
    lda MSB+1, x
    sta MSB+2, x
    lda MSB, x
    sta MSB+1, x
    sty MSB, x
    ldy LSB+2, x
    lda LSB+1, x
    sta LSB+2, x
    lda LSB, x
    sta LSB+1, x
    sty LSB, x
    rts ;code)";

static const char over[] = R"(:code over
    dex
    lda MSB + 2, x
    sta MSB, x
    lda LSB + 2, x
    sta LSB, x
    rts ;code)";

static const char qdup[] = R"(:code ?dup
    lda MSB,x
    ora LSB,x
    beq +
    dex
    lda MSB + 1, x
    sta MSB, x
    lda LSB + 1, x
    sta LSB, x
+   rts ;code)";

static const char dup[] = R"(:code dup
    dex
    lda MSB + 1, x
    sta MSB, x
    lda LSB + 1, x
    sta LSB, x
    rts ;code)";

static const char twodup[] = R"(: 2dup over over ;)";

static const char equal[] = R"(:code =
    ldy #0
    lda LSB, x
    cmp LSB + 1, x
    bne +
    lda MSB, x
    cmp MSB + 1, x
    bne +
    dey
+   inx
    sty MSB, x
    sty LSB, x
    rts ;code)";

static const char zequal[] = R"(:code 0=
    ldy #0
    lda MSB, x
    bne +
    lda LSB, x
    bne +
    dey
+   sty MSB, x
    sty LSB, x
    rts ;code)";

static const char and_[] = R"(:code and
    lda MSB, x
    and MSB + 1, x
    sta MSB + 1, x

    lda LSB, x
    and LSB + 1, x
    sta LSB + 1, x

    inx
    rts ;code)";

static const char store[] = R"(:code !
    lda LSB, x
    sta W
    lda MSB, x
    sta W + 1

    ldy #0
    lda LSB+1, x
    sta (W), y
    iny
    lda MSB+1, x
    sta (W), y

    inx
    inx
    rts ;code)";

static const char fetch[] = R"(:code @
    lda LSB,x
    sta W
    lda MSB,x
    sta W+1

    ldy #0
    lda (W),y
    sta LSB,x
    iny
    lda (W),y
    sta MSB,x
    rts ;code)";

static const char fill[] = R"(:code fill
    lda LSB, x
    tay
    lda LSB + 2, x
    sta .fdst
    lda MSB + 2, x
    sta .fdst + 1
    lda LSB + 1, x
    eor #$ff
    sta W
    lda MSB + 1, x
    eor #$ff
    sta W + 1
    inx
    inx
    inx
-
    inc W
    bne +
    inc W + 1
    bne +
    rts
+
.fdst = * + 1
    sty $ffff ; overwrite

    ; advance
    inc .fdst
    bne -
    inc .fdst + 1
    jmp -)";

static const char ifcmp[] = R"(:code (if)
    inx
    lda MSB-1,x
    ora LSB-1,x
    rts ;code)";

static const char mul[] = ": * m* drop ;";

static const char zless[] = R"(:code 0<
    lda MSB,x
    and #$80
    beq +
    lda #$ff
+   sta MSB,x
    sta LSB,x
    rts ;code)";

static const char twomul[] = R"(:code 2*
    asl LSB,x
    rol MSB,x
    rts ;code)";

static const char depth[] = R"(:code depth
    txa
    eor #$ff
    tay
    iny
    dex
    sty LSB,x
    lda #0
    sta MSB,x
    rts ;code)";

static const char do_[] = R"(:code (do) ; ( limit first -- )
    pla
    sta W
    pla
    tay

    lda MSB+1,x
    pha
    lda LSB+1,x
    pha
    lda MSB,x
    pha
    lda LSB,x
    pha
    inx
    inx

    tya
    pha
    lda W
    pha
    rts ;code)";

static const char rat[] = R"(:code r@
    txa
    tsx
    ldy $103,x
    sty W
    ldy $104,x
    tax
    dex
    sty MSB,x
    lda W
    sta LSB,x
    rts ;code)";

static const char cr[] = ": cr $d emit ;";

static const char emit[] = R"(:code emit
    lda LSB,x
    inx
    jmp $ffd2 ; PUTCHR ;code)";

static const char litstring[] =
    ": (litstring) r> 1+ dup 1+ swap c@ 2dup + 1- >r ;";

static const char tor[] = R"(:code >r
    pla
    sta W
    pla
    sta W+1
    inc W
    bne +
    inc W+1
+
    lda MSB,x
    pha
    lda LSB,x
    pha
    inx
    jmp (W) ;code)";

static const char branch[] = R"(:code (branch)
    pla
    sta W
    pla
    sta W + 1

    ldy #2
    lda (W), y
    sta + + 2
    dey
    lda (W), y
    sta + + 1
+   jmp $1234
;code)";

static const char loop[] = R"(:code (loop)
    stx W
    tsx
    inc 103,x
    bne +
    inc 104,x
+   lda 103,x
    cmp 105,x
    beq +
-
	; loop not finished, return
    ldx W
	rts
+
	lda 104,x
	cmp 106,x
	bne -

	; loop done
	pla
	clc
	adc #4 ; skip loop jmp in calling code
	sta W2
	pla
	adc #0
	sta W2+1
	txa
	clc
	adc #6 ; pop loop counters
	tax
	txs
	ldx W
	jmp (W2) ;code)";

static const char negate[] = ": negate invert 1+ ;";

static const char invert[] = R"(:code invert
    lda MSB,x
    eor #$ff
    sta MSB,x
    lda LSB,x
    eor #$ff
    sta LSB,x
    rts ;code)";

// -----

const char* getDefinition(const char* wordName) {
    struct Pair {
        const char* name;
        const char* definition;
    };
    static const Pair defs[] = {
        { "invert", invert },
        { ">r", tor },
        { "emit", emit },
        { "cr", cr },
        { "r@", rat },
        { "depth", depth },
        { "2*", twomul },
        { "*", mul },
        { "!", store },
        { "+", plus },
        { "-", minus },
        { "0=", zequal },
        { "0<", zless },
        { "1+", oneplus },
        { "1-", oneminus },
        { "2+", twoplus },
        { "2dup", twodup },
        { "=", equal },
        { "@", fetch },
        { "and", and_ },
        { "c!", cstore },
        { "c@", cfetch },
        { "dup", dup },
        { "?dup", qdup },
		{ "fill", fill },
        { "over", over },
        { "rot", rot },
        { "swap", swap },
        { "negate", negate },
        // internal
        { "(loop)", loop },
        { "(do)", do_ },
        { "(lit)", lit },
        { "(litstring)", litstring },
        { "(if)", ifcmp },
        { "(pushya)", pushya },
        { nullptr, nullptr }
    };
    const Pair* it = defs;
    while (it->name) {
        if (!strcmp(it->name, wordName)) {
            return it->definition;
        }
        ++it;
    }
    fprintf(stderr, "Cannot find definition for '%s'\n", wordName);
    exit(1);
    return nullptr;
}
<commit_msg>added quit<commit_after>#include "inbuilt.h"

#include <cstdio>
#include <cstdlib>
#include <cstring>

static const char pushya[] = R"(:code (pushya)
    dex
    sta LSB,x
    sty MSB,x
+   rts ;code)";

static const char oneplus[] = R"(:code 1+
    inc LSB,x
    bne +
    inc MSB,x
+   rts ;code)";

static const char oneminus[] = R"(:code 1-
    lda LSB, x
    bne +
    dec MSB, x
+   dec LSB, x
    rts ;code)";

static const char plus[] = R"(:code +
    lda LSB, x
    clc
    adc LSB + 1, x
    sta LSB + 1, x

    lda MSB, x
    adc MSB + 1, x
    sta MSB + 1, x

    inx
    rts ;code)";

static const char minus[] = R"(:code -
    lda LSB + 1, x
    sec
    sbc LSB, x
    sta LSB + 1, x
    lda MSB + 1, x
    sbc MSB, x
    sta MSB + 1, x
    inx
    rts ;code)";

static const char twoplus[] = R"(: 2+ 1+ 1+ ;)";

static const char cfetch[] = R"(:code c@
    lda LSB,x
    sta + + 1
    lda MSB,x
    sta + + 2
+   lda $cafe
    sta LSB,x
    lda #0
    sta MSB,x
    rts ;code)";

static const char cstore[] = R"(:code c!
    lda LSB,x
    sta + + 1
    lda MSB,x
    sta + + 2
    lda LSB+1,x
+   sta $1234
    inx
    inx
    rts ;code)";

static const char swap[] = R"(:code swap
    ldy MSB, x
    lda MSB + 1, x
    sta MSB, x
    sty MSB + 1, x

    ldy LSB, x
    lda LSB + 1, x
    sta LSB, x
    sty LSB + 1, x
    rts ;code)";

static const char lit[] = R"(:code (lit)
    dex
    pla
    sta W
    pla
    sta W + 1
    ldy #1
    lda (W), y
    sta LSB, x
    iny
    lda (W), y
    sta MSB, x
    lda W
    clc
    adc #3
    sta + + 1
    lda W + 1
    adc #0
    sta + + 2
+   jmp $1234 ;code)";

static const char rot[] = R"(:code rot
    ldy MSB+2, x
    lda MSB+1, x
    sta MSB+2, x
    lda MSB, x
    sta MSB+1, x
    sty MSB, x
    ldy LSB+2, x
    lda LSB+1, x
    sta LSB+2, x
    lda LSB, x
    sta LSB+1, x
    sty LSB, x
    rts ;code)";

static const char over[] = R"(:code over
    dex
    lda MSB + 2, x
    sta MSB, x
    lda LSB + 2, x
    sta LSB, x
    rts ;code)";

static const char qdup[] = R"(:code ?dup
    lda MSB,x
    ora LSB,x
    beq +
    dex
    lda MSB + 1, x
    sta MSB, x
    lda LSB + 1, x
    sta LSB, x
+   rts ;code)";

static const char dup[] = R"(:code dup
    dex
    lda MSB + 1, x
    sta MSB, x
    lda LSB + 1, x
    sta LSB, x
    rts ;code)";

static const char twodup[] = R"(: 2dup over over ;)";

static const char equal[] = R"(:code =
    ldy #0
    lda LSB, x
    cmp LSB + 1, x
    bne +
    lda MSB, x
    cmp MSB + 1, x
    bne +
    dey
+   inx
    sty MSB, x
    sty LSB, x
    rts ;code)";

static const char zequal[] = R"(:code 0=
    ldy #0
    lda MSB, x
    bne +
    lda LSB, x
    bne +
    dey
+   sty MSB, x
    sty LSB, x
    rts ;code)";

static const char and_[] = R"(:code and
    lda MSB, x
    and MSB + 1, x
    sta MSB + 1, x

    lda LSB, x
    and LSB + 1, x
    sta LSB + 1, x

    inx
    rts ;code)";

static const char store[] = R"(:code !
    lda LSB, x
    sta W
    lda MSB, x
    sta W + 1

    ldy #0
    lda LSB+1, x
    sta (W), y
    iny
    lda MSB+1, x
    sta (W), y

    inx
    inx
    rts ;code)";

static const char fetch[] = R"(:code @
    lda LSB,x
    sta W
    lda MSB,x
    sta W+1

    ldy #0
    lda (W),y
    sta LSB,x
    iny
    lda (W),y
    sta MSB,x
    rts ;code)";

static const char fill[] = R"(:code fill
    lda LSB, x
    tay
    lda LSB + 2, x
    sta .fdst
    lda MSB + 2, x
    sta .fdst + 1
    lda LSB + 1, x
    eor #$ff
    sta W
    lda MSB + 1, x
    eor #$ff
    sta W + 1
    inx
    inx
    inx
-
    inc W
    bne +
    inc W + 1
    bne +
    rts
+
.fdst = * + 1
    sty $ffff ; overwrite

    ; advance
    inc .fdst
    bne -
    inc .fdst + 1
    jmp -)";

static const char ifcmp[] = R"(:code (if)
    inx
    lda MSB-1,x
    ora LSB-1,x
    rts ;code)";

static const char mul[] = ": * m* drop ;";

static const char zless[] = R"(:code 0<
    lda MSB,x
    and #$80
    beq +
    lda #$ff
+   sta MSB,x
    sta LSB,x
    rts ;code)";

static const char twomul[] = R"(:code 2*
    asl LSB,x
    rol MSB,x
    rts ;code)";

static const char depth[] = R"(:code depth
    txa
    eor #$ff
    tay
    iny
    dex
    sty LSB,x
    lda #0
    sta MSB,x
    rts ;code)";

static const char do_[] = R"(:code (do) ; ( limit first -- )
    pla
    sta W
    pla
    tay

    lda MSB+1,x
    pha
    lda LSB+1,x
    pha
    lda MSB,x
    pha
    lda LSB,x
    pha
    inx
    inx

    tya
    pha
    lda W
    pha
    rts ;code)";

static const char rat[] = R"(:code r@
    txa
    tsx
    ldy $103,x
    sty W
    ldy $104,x
    tax
    dex
    sty MSB,x
    lda W
    sta LSB,x
    rts ;code)";

static const char cr[] = ": cr $d emit ;";

static const char emit[] = R"(:code emit
    lda LSB,x
    inx
    jmp $ffd2 ; PUTCHR ;code)";

static const char litstring[] =
    ": (litstring) r> 1+ dup 1+ swap c@ 2dup + 1- >r ;";

static const char tor[] = R"(:code >r
    pla
    sta W
    pla
    sta W+1
    inc W
    bne +
    inc W+1
+
    lda MSB,x
    pha
    lda LSB,x
    pha
    inx
    jmp (W) ;code)";

static const char branch[] = R"(:code (branch)
    pla
    sta W
    pla
    sta W + 1

    ldy #2
    lda (W), y
    sta + + 2
    dey
    lda (W), y
    sta + + 1
+   jmp $1234
;code)";

static const char loop[] = R"(:code (loop)
    stx W
    tsx
    inc 103,x
    bne +
    inc 104,x
+   lda 103,x
    cmp 105,x
    beq +
-
	; loop not finished, return
    ldx W
	rts
+
	lda 104,x
	cmp 106,x
	bne -

	; loop done
	pla
	clc
	adc #4 ; skip loop jmp in calling code
	sta W2
	pla
	adc #0
	sta W2+1
	txa
	clc
	adc #6 ; pop loop counters
	tax
	txs
	ldx W
	jmp (W2) ;code)";

static const char negate[] = ": negate invert 1+ ;";

static const char invert[] = R"(:code invert
    lda MSB,x
    eor #$ff
    sta MSB,x
    lda LSB,x
    eor #$ff
    sta LSB,x
    rts ;code)";

static const char quit[] = R"(:code quit
    ldx #$ff
    txs
    rts ;code)";

// -----

const char* getDefinition(const char* wordName) {
    struct Pair {
        const char* name;
        const char* definition;
    };
    static const Pair defs[] = {
        { "quit", quit },
        { "invert", invert },
        { ">r", tor },
        { "emit", emit },
        { "cr", cr },
        { "r@", rat },
        { "depth", depth },
        { "2*", twomul },
        { "*", mul },
        { "!", store },
        { "+", plus },
        { "-", minus },
        { "0=", zequal },
        { "0<", zless },
        { "1+", oneplus },
        { "1-", oneminus },
        { "2+", twoplus },
        { "2dup", twodup },
        { "=", equal },
        { "@", fetch },
        { "and", and_ },
        { "c!", cstore },
        { "c@", cfetch },
        { "dup", dup },
        { "?dup", qdup },
		{ "fill", fill },
        { "over", over },
        { "rot", rot },
        { "swap", swap },
        { "negate", negate },
        // internal
        { "(loop)", loop },
        { "(do)", do_ },
        { "(lit)", lit },
        { "(litstring)", litstring },
        { "(if)", ifcmp },
        { "(pushya)", pushya },
        { nullptr, nullptr }
    };
    const Pair* it = defs;
    while (it->name) {
        if (!strcmp(it->name, wordName)) {
            return it->definition;
        }
        ++it;
    }
    fprintf(stderr, "Cannot find definition for '%s'\n", wordName);
    exit(1);
    return nullptr;
}
<|endoftext|>


<commit_before>#include <turner/msturn>
#include <turner/test>
#include <catch2/generators/catch_generators.hpp>

namespace {

using namespace turner_test;

TEST_CASE("msturn")
{
	SECTION("method registry")
	{
		CHECK(turner::msturn::allocate == 0x0003);
		CHECK(turner::msturn::allocate_success == 0x0103);
		CHECK(turner::msturn::allocate_error == 0x0113);
		CHECK(turner::msturn::send_request == 0x0004);
		CHECK(turner::msturn::data_indication == 0x0115);
		CHECK(turner::msturn::set_active_destination == 0x0006);
		CHECK(turner::msturn::set_active_destination_success == 0x0106);
		CHECK(turner::msturn::set_active_destination_error == 0x0116);
	}

	SECTION("attribute registry")
	{
		CHECK(turner::msturn::mapped_address == 0x0001);
		CHECK(turner::msturn::username == 0x0006);
		CHECK(turner::msturn::message_integrity == 0x0008);
		CHECK(turner::msturn::error_code == 0x0009);
		CHECK(turner::msturn::unknown_attributes == 0x000a);
		CHECK(turner::msturn::lifetime == 0x000d);
		CHECK(turner::msturn::alternate_server == 0x000e);
		CHECK(turner::msturn::bandwidth == 0x0010);
		CHECK(turner::msturn::destination_address == 0x0011);
		CHECK(turner::msturn::remote_address == 0x0012);
		CHECK(turner::msturn::data == 0x0013);
		CHECK(turner::msturn::nonce == 0x0014);
		CHECK(turner::msturn::realm == 0x0015);
		CHECK(turner::msturn::requested_address_family == 0x0017);
		CHECK(turner::msturn::ms_version == 0x8008);
		CHECK(turner::msturn::xor_mapped_address == 0x8020);
		CHECK(turner::msturn::ms_alternate_host_name == 0x8032);
		CHECK(turner::msturn::app_id == 0x8037);
		CHECK(turner::msturn::secure_tag == 0x8039);
		CHECK(turner::msturn::ms_sequence_number == 0x8050);
		CHECK(turner::msturn::ms_service_quality == 0x8055);
		CHECK(turner::msturn::ms_alternate_mapped_address == 0x8090);
		CHECK(turner::msturn::multiplexed_session_id == 0x8095);
	}
}

} // namespace
<commit_msg>Make Catch2 and MSVC play nice together<commit_after>#include <turner/msturn>
#include <turner/test>
#include <catch2/generators/catch_generators.hpp>

namespace {

using namespace turner_test;

TEST_CASE("msturn")
{
	SECTION("method registry")
	{
		CHECK(turner::msturn::allocate == 0x0003_u16);
		CHECK(turner::msturn::allocate_success == 0x0103_u16);
		CHECK(turner::msturn::allocate_error == 0x0113_u16);
		CHECK(turner::msturn::send_request == 0x0004_u16);
		CHECK(turner::msturn::data_indication == 0x0115_u16);
		CHECK(turner::msturn::set_active_destination == 0x0006_u16);
		CHECK(turner::msturn::set_active_destination_success == 0x0106_u16);
		CHECK(turner::msturn::set_active_destination_error == 0x0116_u16);
	}

	SECTION("attribute registry")
	{
		CHECK(turner::msturn::mapped_address == 0x0001_u16);
		CHECK(turner::msturn::username == 0x0006_u16);
		CHECK(turner::msturn::message_integrity == 0x0008_u16);
		CHECK(turner::msturn::error_code == 0x0009_u16);
		CHECK(turner::msturn::unknown_attributes == 0x000a_u16);
		CHECK(turner::msturn::lifetime == 0x000d_u16);
		CHECK(turner::msturn::alternate_server == 0x000e_u16);
		CHECK(turner::msturn::bandwidth == 0x0010_u16);
		CHECK(turner::msturn::destination_address == 0x0011_u16);
		CHECK(turner::msturn::remote_address == 0x0012_u16);
		CHECK(turner::msturn::data == 0x0013_u16);
		CHECK(turner::msturn::nonce == 0x0014_u16);
		CHECK(turner::msturn::realm == 0x0015_u16);
		CHECK(turner::msturn::requested_address_family == 0x0017_u16);
		CHECK(turner::msturn::ms_version == 0x8008_u16);
		CHECK(turner::msturn::xor_mapped_address == 0x8020_u16);
		CHECK(turner::msturn::ms_alternate_host_name == 0x8032_u16);
		CHECK(turner::msturn::app_id == 0x8037_u16);
		CHECK(turner::msturn::secure_tag == 0x8039_u16);
		CHECK(turner::msturn::ms_sequence_number == 0x8050_u16);
		CHECK(turner::msturn::ms_service_quality == 0x8055_u16);
		CHECK(turner::msturn::ms_alternate_mapped_address == 0x8090_u16);
		CHECK(turner::msturn::multiplexed_session_id == 0x8095_u16);
	}
}

} // namespace
<|endoftext|>


<commit_before>/*
Copyright (C) 2013,2018 Rodrigo Jose Hernandez Cordoba

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

#include <cstring>
#include <cstdio>
#include <cassert>
#include "zlib.h"
#include "aeongames/Package.h"
#include "aeongames/CRC.h"

namespace AeonGames
{
#define CHUNK 16384
    /* Decompress from file source to memory dest until stream ends or EOF.
       read_inflated_data() returns Z_OK on success, Z_MEM_ERROR if memory
       could not be allocated for processing, Z_DATA_ERROR if the deflate data is
       invalid or incomplete, Z_VERSION_ERROR if the version of zlib.h and
       the version of the library linked do not match, or Z_ERRNO if there
       is an error reading or writing the files. */
    static int read_inflated_data ( FILE* source, uint8_t* buffer, uint32_t buffer_size )
    {
        int ret;
        z_stream strm;
        unsigned char in[CHUNK];

        /* allocate inflate state */
        strm.zalloc = Z_NULL;
        strm.zfree = Z_NULL;
        strm.opaque = Z_NULL;
        strm.avail_in = 0;
        strm.next_in = Z_NULL;
        ret = inflateInit ( &strm );
        if ( ret != Z_OK )
        {
            return ret;
        }
        strm.avail_out = buffer_size;
        strm.next_out = buffer;

        /* decompress until deflate stream ends or end of file */
        do
        {
            strm.avail_in = static_cast<uInt> ( fread ( in, 1, CHUNK, source ) );
            if ( ferror ( source ) )
            {
                ( void ) inflateEnd ( &strm );
                return Z_ERRNO;
            }
            if ( strm.avail_in == 0 )
            {
                break;
            }
            strm.next_in = in;
            ret = inflate ( &strm, Z_NO_FLUSH );
            assert ( ret != Z_STREAM_ERROR ); /* state not clobbered */
            switch ( ret )
            {
            case Z_NEED_DICT:
                ret = Z_DATA_ERROR;     /* and fall through */
            case Z_DATA_ERROR:
            case Z_MEM_ERROR:
                ( void ) inflateEnd ( &strm );
                return ret;
            }

            /* done when inflate() says it's done */
        }
        while ( ret != Z_STREAM_END );

        /* clean up and return */
        ( void ) inflateEnd ( &strm );
        return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR;
    }
    static int CompareDirectoryEntries ( const void * A, const void * B )
    {
        const uint32_t a = *reinterpret_cast<const uint32_t*> ( A );
        const PKGDirectoryEntry* b = reinterpret_cast<const PKGDirectoryEntry*> ( B );
        if ( a > b->path )
        {
            return 1;
        }
        else if ( a < b->path )
        {
            return -1;
        }
        return 0;
    }

    Package::Package() : mHeader{}, mHandle{}, mDirectory{}, mStringTable{}
    {
    }

    Package::~Package()
    {
        Close();
    }

    bool Package::Open ( const char* filename )
    {
        Close();
        if ( ( mHandle = fopen ( filename, "rb" ) ) == nullptr )
        {
            //AEONGAMES_LOG_ERROR ( "Could not open file %s", filename );
            return false;
        }
        fread ( &mHeader, sizeof ( PKGHeader ), 1, mHandle );
        if ( strncmp ( mHeader.id, "AEONPKG\0", 8 ) != 0 )
        {
            Close();
            return false;
        }
        mDirectory.resize ( mHeader.file_count );
        for ( uint32_t i = 0; i < mHeader.file_count; ++i )
        {
            fread ( &mDirectory[i], sizeof ( PKGDirectoryEntry ), 1, mHandle );
        }
        mStringTable.resize ( mHeader.file_size - mHeader.string_table_offset );
        fseek ( mHandle, mHeader.string_table_offset, SEEK_SET );
        fread ( mStringTable.data(), sizeof ( uint8_t ), mHeader.file_size - mHeader.string_table_offset, mHandle );
        return true;
    }

    void Package::Close()
    {
        if ( mHandle != nullptr )
        {
            fclose ( mHandle );
            mHandle = nullptr;
        }
        mDirectory.clear();
        mStringTable.clear();
        memset ( &mHeader, 0, sizeof ( PKGHeader ) );
    }

    uint32_t Package::GetFileCount() const
    {
        return mHeader.file_count;
    }

    uint32_t Package::GetFileSize ( uint32_t crc ) const
    {
        PKGDirectoryEntry* directory_entry =
            reinterpret_cast<PKGDirectoryEntry*> (
                bsearch ( &crc,
                          mDirectory.data(),
                          mHeader.file_count,
                          sizeof ( PKGDirectoryEntry ),
                          CompareDirectoryEntries ) );
        if ( directory_entry != nullptr )
        {
            return directory_entry->uncompressed_size;
        }
        return 0;
    }

    const PKGDirectoryEntry* Package::GetFileByIndex ( uint32_t index ) const
    {
        return ( index < mHeader.file_count ) ? &mDirectory[index] : nullptr;
    }

    struct StringTableEntry
    {
        uint32_t CRC;     /// String CRC
        uint32_t offset;  /// String Offset
    };

    static int CompareCRCs ( const void * A, const void * B )
    {
        const uint32_t a = *reinterpret_cast<const uint32_t*> ( A );
        const StringTableEntry* b = reinterpret_cast<const StringTableEntry*> ( B );
        if ( a > b->CRC )
        {
            return 1;
        }
        else if ( a < b->CRC )
        {
            return -1;
        }
        return 0;
    }

    const char* Package::GetFilePath ( uint32_t crc ) const
    {
        StringTableEntry* entry =
            reinterpret_cast<StringTableEntry*> (
                bsearch ( &crc,
                          mStringTable.data() + sizeof ( uint32_t ),
                          *reinterpret_cast<const uint32_t*> ( mStringTable.data() ),
                          sizeof ( StringTableEntry ),
                          CompareCRCs ) );
        if ( entry != NULL )
        {
            return reinterpret_cast<const char*> ( mStringTable.data() ) + entry->offset;
        }
        return nullptr;
    }

    const PKGDirectoryEntry* Package::ContainsFile ( uint32_t crc ) const
    {
        PKGDirectoryEntry* directory_entry =
            reinterpret_cast<PKGDirectoryEntry*> (
                bsearch ( &crc,
                          mDirectory.data(),
                          mHeader.file_count,
                          sizeof ( PKGDirectoryEntry ),
                          CompareDirectoryEntries ) );
        return directory_entry;
    }

    bool Package::LoadFile ( uint32_t crc, uint8_t* buffer, uint32_t buffer_size ) const
    {
        PKGDirectoryEntry* directory_entry =
            reinterpret_cast<PKGDirectoryEntry*> (
                bsearch ( &crc,
                          mDirectory.data(),
                          mHeader.file_count,
                          sizeof ( PKGDirectoryEntry ),
                          CompareDirectoryEntries ) );
        if ( directory_entry == nullptr )
        {
            return false;
        }
        if ( directory_entry->uncompressed_size < buffer_size )
        {
            //AEONGAMES_LOG_ERROR ( "Insuficient Buffer Size in %s line %i.", __FUNCTION__, __LINE__ );
            return false;
        }
        if ( !fseek ( mHandle, directory_entry->offset, SEEK_SET ) )
        {
            return false;
        }
        switch ( directory_entry->compression_type )
        {
        case NONE:
            if ( fread ( buffer, buffer_size, 1, mHandle ) == 0 )
            {
                //AEONGAMES_LOG_ERROR ( "fread Failed in %s line %i.", __FUNCTION__, __LINE__ );
                return false;
            }
            break;
        case ZLIB:
            if ( read_inflated_data ( mHandle, buffer, buffer_size ) != Z_OK )
            {
                //AEONGAMES_LOG_ERROR ( "fread Failed in %s line %i.", __FUNCTION__, __LINE__ );
                return false;
            }
            break;
        default:
            //AEONGAMES_LOG_ERROR ( "Unrecognized compression type, or type not supported: %i", directory_entry->compression_type );
            return false;
        }
        return true;
    }
}
<commit_msg>Linux Build Fix<commit_after>/*
Copyright (C) 2013,2018 Rodrigo Jose Hernandez Cordoba

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <cassert>
#include "zlib.h"
#include "aeongames/Package.h"
#include "aeongames/CRC.h"

namespace AeonGames
{
#define CHUNK 16384
    /* Decompress from file source to memory dest until stream ends or EOF.
       read_inflated_data() returns Z_OK on success, Z_MEM_ERROR if memory
       could not be allocated for processing, Z_DATA_ERROR if the deflate data is
       invalid or incomplete, Z_VERSION_ERROR if the version of zlib.h and
       the version of the library linked do not match, or Z_ERRNO if there
       is an error reading or writing the files. */
    static int read_inflated_data ( FILE* source, uint8_t* buffer, uint32_t buffer_size )
    {
        int ret;
        z_stream strm;
        unsigned char in[CHUNK];

        /* allocate inflate state */
        strm.zalloc = Z_NULL;
        strm.zfree = Z_NULL;
        strm.opaque = Z_NULL;
        strm.avail_in = 0;
        strm.next_in = Z_NULL;
        ret = inflateInit ( &strm );
        if ( ret != Z_OK )
        {
            return ret;
        }
        strm.avail_out = buffer_size;
        strm.next_out = buffer;

        /* decompress until deflate stream ends or end of file */
        do
        {
            strm.avail_in = static_cast<uInt> ( fread ( in, 1, CHUNK, source ) );
            if ( ferror ( source ) )
            {
                ( void ) inflateEnd ( &strm );
                return Z_ERRNO;
            }
            if ( strm.avail_in == 0 )
            {
                break;
            }
            strm.next_in = in;
            ret = inflate ( &strm, Z_NO_FLUSH );
            assert ( ret != Z_STREAM_ERROR ); /* state not clobbered */
            switch ( ret )
            {
            case Z_NEED_DICT:
                ret = Z_DATA_ERROR;     /* and fall through */
            case Z_DATA_ERROR:
            case Z_MEM_ERROR:
                ( void ) inflateEnd ( &strm );
                return ret;
            }

            /* done when inflate() says it's done */
        }
        while ( ret != Z_STREAM_END );

        /* clean up and return */
        ( void ) inflateEnd ( &strm );
        return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR;
    }
    static int CompareDirectoryEntries ( const void * A, const void * B )
    {
        const uint32_t a = *reinterpret_cast<const uint32_t*> ( A );
        const PKGDirectoryEntry* b = reinterpret_cast<const PKGDirectoryEntry*> ( B );
        if ( a > b->path )
        {
            return 1;
        }
        else if ( a < b->path )
        {
            return -1;
        }
        return 0;
    }

    Package::Package() : mHeader{}, mHandle{}, mDirectory{}, mStringTable{}
    {
    }

    Package::~Package()
    {
        Close();
    }

    bool Package::Open ( const char* filename )
    {
        Close();
        if ( ( mHandle = fopen ( filename, "rb" ) ) == nullptr )
        {
            //AEONGAMES_LOG_ERROR ( "Could not open file %s", filename );
            return false;
        }
        fread ( &mHeader, sizeof ( PKGHeader ), 1, mHandle );
        if ( strncmp ( mHeader.id, "AEONPKG\0", 8 ) != 0 )
        {
            Close();
            return false;
        }
        mDirectory.resize ( mHeader.file_count );
        for ( uint32_t i = 0; i < mHeader.file_count; ++i )
        {
            fread ( &mDirectory[i], sizeof ( PKGDirectoryEntry ), 1, mHandle );
        }
        mStringTable.resize ( mHeader.file_size - mHeader.string_table_offset );
        fseek ( mHandle, mHeader.string_table_offset, SEEK_SET );
        fread ( mStringTable.data(), sizeof ( uint8_t ), mHeader.file_size - mHeader.string_table_offset, mHandle );
        return true;
    }

    void Package::Close()
    {
        if ( mHandle != nullptr )
        {
            fclose ( mHandle );
            mHandle = nullptr;
        }
        mDirectory.clear();
        mStringTable.clear();
        memset ( &mHeader, 0, sizeof ( PKGHeader ) );
    }

    uint32_t Package::GetFileCount() const
    {
        return mHeader.file_count;
    }

    uint32_t Package::GetFileSize ( uint32_t crc ) const
    {
        PKGDirectoryEntry* directory_entry =
            reinterpret_cast<PKGDirectoryEntry*> (
                bsearch ( &crc,
                          mDirectory.data(),
                          mHeader.file_count,
                          sizeof ( PKGDirectoryEntry ),
                          CompareDirectoryEntries ) );
        if ( directory_entry != nullptr )
        {
            return directory_entry->uncompressed_size;
        }
        return 0;
    }

    const PKGDirectoryEntry* Package::GetFileByIndex ( uint32_t index ) const
    {
        return ( index < mHeader.file_count ) ? &mDirectory[index] : nullptr;
    }

    struct StringTableEntry
    {
        uint32_t CRC;     /// String CRC
        uint32_t offset;  /// String Offset
    };

    static int CompareCRCs ( const void * A, const void * B )
    {
        const uint32_t a = *reinterpret_cast<const uint32_t*> ( A );
        const StringTableEntry* b = reinterpret_cast<const StringTableEntry*> ( B );
        if ( a > b->CRC )
        {
            return 1;
        }
        else if ( a < b->CRC )
        {
            return -1;
        }
        return 0;
    }

    const char* Package::GetFilePath ( uint32_t crc ) const
    {
        StringTableEntry* entry =
            reinterpret_cast<StringTableEntry*> (
                bsearch ( &crc,
                          mStringTable.data() + sizeof ( uint32_t ),
                          *reinterpret_cast<const uint32_t*> ( mStringTable.data() ),
                          sizeof ( StringTableEntry ),
                          CompareCRCs ) );
        if ( entry != NULL )
        {
            return reinterpret_cast<const char*> ( mStringTable.data() ) + entry->offset;
        }
        return nullptr;
    }

    const PKGDirectoryEntry* Package::ContainsFile ( uint32_t crc ) const
    {
        PKGDirectoryEntry* directory_entry =
            reinterpret_cast<PKGDirectoryEntry*> (
                bsearch ( &crc,
                          mDirectory.data(),
                          mHeader.file_count,
                          sizeof ( PKGDirectoryEntry ),
                          CompareDirectoryEntries ) );
        return directory_entry;
    }

    bool Package::LoadFile ( uint32_t crc, uint8_t* buffer, uint32_t buffer_size ) const
    {
        PKGDirectoryEntry* directory_entry =
            reinterpret_cast<PKGDirectoryEntry*> (
                bsearch ( &crc,
                          mDirectory.data(),
                          mHeader.file_count,
                          sizeof ( PKGDirectoryEntry ),
                          CompareDirectoryEntries ) );
        if ( directory_entry == nullptr )
        {
            return false;
        }
        if ( directory_entry->uncompressed_size < buffer_size )
        {
            //AEONGAMES_LOG_ERROR ( "Insuficient Buffer Size in %s line %i.", __FUNCTION__, __LINE__ );
            return false;
        }
        if ( !fseek ( mHandle, directory_entry->offset, SEEK_SET ) )
        {
            return false;
        }
        switch ( directory_entry->compression_type )
        {
        case NONE:
            if ( fread ( buffer, buffer_size, 1, mHandle ) == 0 )
            {
                //AEONGAMES_LOG_ERROR ( "fread Failed in %s line %i.", __FUNCTION__, __LINE__ );
                return false;
            }
            break;
        case ZLIB:
            if ( read_inflated_data ( mHandle, buffer, buffer_size ) != Z_OK )
            {
                //AEONGAMES_LOG_ERROR ( "fread Failed in %s line %i.", __FUNCTION__, __LINE__ );
                return false;
            }
            break;
        default:
            //AEONGAMES_LOG_ERROR ( "Unrecognized compression type, or type not supported: %i", directory_entry->compression_type );
            return false;
        }
        return true;
    }
}
<|endoftext|>


<commit_before>//	Simple Chatterbox client written in C++
//	Depends on boost 1.55 and MinGW.
//
//	To build on Windows 64-bit systems, we used the excellent MinGW Distro
//	from nuwen.net. Build command is:
//		g++ -std=c++0x -Wall -o cbclient cbclient.cpp -lboost_thread -lboost_system -lws2_32
//
//	When building on Windows XP SP3, define NTDDI_VERSION=0x05010300.
//	The build command becomes:
//		g++ -std=c++0x -Wall -DNTDDI_VERSION=0x05010300 -o cbclient cbclient.cpp -lboost_thread -lboost_system -lws2_32
//
//	If you are not using the MinGW Distro from nuwen.net, you'll need to
//	build the Boost libraries yourself. This could possibly be a difficult
//	but worthy task. Be strong.
//
//	Caution when building Boost 1.55 under MinGW on XP. You SHOULD convert the build.bat
//	from Unix line endings to DOS line endings and you MUST ensure that the TMP and
//	TEMP user variables do not point to directories names that have spaces in them.
//
//	Usage:
//		cbclient <chatterbox-host> [<chatterbox-port>]
//		Default chatterbox-port is 20000
//
#include <iostream>
#include <string>
#include <sstream>
#include <array>

#include <boost/thread.hpp>
#include <boost/asio.hpp>

using std::cout;
using std::cin;
using std::cerr;
using std::endl;
using std::string;

using boost::asio::ip::tcp;

bool get_cmdline_args(int argc, char* argv[], string &host, string &port);
string socket_gets(tcp::socket& socket);
void socket_puts(tcp::socket& socket, const string& msg);

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

	string host, port;

	if(get_cmdline_args(argc, argv, host, port) == false) {
		cout << "Usage: cbclient <chatterbox-host> [<chatterbox-port>]";
		return 1;
	}

	try {

		cout << "Connecting to chatterbox server at " << host << ':' << port << endl;

		boost::asio::io_service io_service;
		tcp::resolver resolver(io_service);
		tcp::resolver::query query(host, port);
		auto endpoint_iterator = resolver.resolve(query);

		tcp::socket socket(io_service);
		boost::asio::connect(socket, endpoint_iterator);

		//	Read and display the chatterbox welcome message.
		cout << socket_gets(socket) << endl;

		//	Let user enter an id
		string user_id;
		getline(cin, user_id);

		//	Send the user ID
		socket_puts(socket, user_id);

		//	Say goodbye
		socket_puts(socket, "bye");
	}
	catch (std::exception& e) {
		cerr << e.what() << endl;
	}

	//boost::thread t;
	return 0;
}

string socket_gets(tcp::socket& socket) {

	std::array<char, 512> buf;
	boost::system::error_code error;

	size_t len = socket.read_some(boost::asio::buffer(buf), error);
	if(error)
		throw boost::system::system_error(error);

	std::stringstream ss;
	ss.write(buf.data(), len);
	return ss.str();
}

void socket_puts(tcp::socket& socket, const string& msg) {
	// boost::system::error_code ignored_error;
	boost::asio::write(socket, boost::asio::buffer(msg) /*, ignored_error*/);
}

bool get_cmdline_args(int argc, char* argv[], string &host, string &port) {

	if(argc < 2 || argc > 3) {
		return false;
	}

	if(argc > 1) {
		host = argv[1];
	}

	port = "20000";
	if(argc > 2) {
		port = argv[2];
	}

	return true;
}
<commit_msg>Add listen and send threads.<commit_after>//	Simple Chatterbox client written in C++
//	Depends on boost 1.55 and MinGW.
//
//	To build on Windows 64-bit systems, we used the excellent MinGW Distro
//	from nuwen.net. Build command is:
//		g++ -std=c++0x -Wall -o cbclient cbclient.cpp -lboost_thread -lboost_system -lws2_32
//
//	When building on Windows XP SP3, define NTDDI_VERSION=0x05010300.
//	The build command becomes:
//		g++ -std=c++0x -Wall -DNTDDI_VERSION=0x05010300 -o cbclient cbclient.cpp -lboost_thread -lboost_system -lws2_32
//
//	If you are not using the MinGW Distro from nuwen.net, you'll need to
//	build the Boost libraries yourself. This could possibly be a difficult
//	but worthy task. Be strong.
//
//	Caution when building Boost 1.55 under MinGW on XP. You SHOULD convert the build.bat
//	from Unix line endings to DOS line endings and you MUST ensure that the TMP and
//	TEMP user variables do not point to directory names that have spaces in them.
//
//	Usage:
//		cbclient <chatterbox-host> [<chatterbox-port>]
//		Default chatterbox-port is 20000
//
#include <iostream>
#include <string>
#include <sstream>
#include <array>

#include <boost/thread.hpp>
#include <boost/asio.hpp>

using std::ostream;
using std::cout;
using std::cin;
using std::cerr;
using std::endl;
using std::string;

using boost::asio::ip::tcp;

bool get_cmdline_args(int argc, char* argv[], string &host, string &port);
string socket_gets(tcp::socket& socket);
void socket_puts(tcp::socket& socket, const string& msg);
void do_listen(tcp::socket& socket);
void do_talk(tcp::socket& socket);
string chomp(const string& s);
void put_to_stream(ostream& o, const string& s);

//	Ugh, I know, global variables, but this will change. We're experimenting
//		for now.
bool done_chatting = false;
boost::mutex done_chatting_mtx;
boost::mutex output_mtx;
bool get_done_chatting();
void set_done_chatting();

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

	string host, port;

	if(get_cmdline_args(argc, argv, host, port) == false) {
		cout << "Usage: cbclient <chatterbox-host> [<chatterbox-port>]";
		return 1;
	}

	try {

		cout << "Connecting to chatterbox server at " << host << ':' << port << endl;

		boost::asio::io_service io_service;
		tcp::resolver resolver(io_service);
		tcp::resolver::query query(host, port);
		auto endpoint_iterator = resolver.resolve(query);

		tcp::socket socket(io_service);
		boost::asio::connect(socket, endpoint_iterator);

		//	Read and display the chatterbox welcome message.
		cout << socket_gets(socket) << endl;

		//	Let user enter an id
		string user_id;
		getline(cin, user_id);
		user_id += '\n';

		//	Send the user ID
		socket_puts(socket, user_id);

		cout << done_chatting << endl;

		boost::thread listen_thread(do_listen, boost::ref(socket));
		boost::thread talk_thread(do_talk, boost::ref(socket));

		listen_thread.join();
		talk_thread.join();
	}
	catch (std::exception& e) {
		cerr << e.what() << endl;
	}

	return 0;
}

void do_listen(tcp::socket& socket) {
	cout << "In do_listen()" << endl;
	while(!get_done_chatting()) {
		string msg_received = socket_gets(socket);
		cout << '<' << chomp(msg_received) << '>' << endl;

		if(msg_received == "bye") {
			set_done_chatting();
		}
	}
}

void do_talk(tcp::socket& socket) {
	cout << "In do_talk()" << endl;
	while(!get_done_chatting()) {
		string msg_to_send;
		getline(cin, msg_to_send);
		msg_to_send += '\n';

		socket_puts(socket, msg_to_send);

		if(chomp(msg_to_send) == "bye") {
			set_done_chatting();
		}
	}
}

void put_to_stream(ostream& o, const string& s) {
	boost::lock_guard<boost::mutex> guard(output_mtx);
	o << s;
}

string chomp(const string& s) {

	const std::string whitespaces (" \t\f\v\n\r");
	string chomped = s;

	std::size_t found = chomped.find_last_not_of(whitespaces);
	if (found != std::string::npos)
		chomped.erase(found+1);
	else
		chomped.clear();

	return chomped;
}

bool get_done_chatting() {
	boost::lock_guard<boost::mutex> guard(done_chatting_mtx);
	return done_chatting;
}

void set_done_chatting() {
	boost::lock_guard<boost::mutex> guard(done_chatting_mtx);
	done_chatting = true;
}

string socket_gets(tcp::socket& socket) {

	std::array<char, 512> buf;
	boost::system::error_code error;

	size_t len = socket.read_some(boost::asio::buffer(buf), error);
	if(error)
		throw boost::system::system_error(error);

	std::stringstream ss;
	ss.write(buf.data(), len);
	return ss.str();
}

void socket_puts(tcp::socket& socket, const string& msg) {
	// boost::system::error_code ignored_error;
	boost::asio::write(socket, boost::asio::buffer(msg) /*, ignored_error*/);
}

bool get_cmdline_args(int argc, char* argv[], string &host, string &port) {

	if(argc < 2 || argc > 3) {
		return false;
	}

	if(argc > 1) {
		host = argv[1];
	}

	port = "20000";
	if(argc > 2) {
		port = argv[2];
	}

	return true;
}
<|endoftext|>


<commit_before>/*
 *    hdfs_wfx.cpp file written and maintained by Calin Cocan
 *    Created on: May 15, 2015
 *
 *    Double Commander
 *   -------------------------------------------------------------------------
 *   WFX plugin for working with HDFS
 *
 *   Based on:
 *     GVFS plugin for Double Commander
 *     Copyright (C) 2009-2010  Koblov Alexander (Alexx2000@mail.ru)
 *
 *     and
 *
 *     GVFS plugin for Tux Commander
 *     Copyright (C) 2008-2009 Tomas Bzatek <tbzatek@users.sourceforge.net>*
 *
 *
 * This work is free: you can redistribute it and/or modify it under the terms of Apache License Version 2.0
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the License for more details.
 * You should have received a copy of the License along with this program. If not, see <http://choosealicense.com/licenses/apache-2.0/>.

 ********************************************************************************************************************* */

#include "wfxplugin.h"
#include <stddef.h>
#include <string.h>
#include "JVMState.h"
#include "gendef.h"
#include "Logger.h"
#include "Utilities.h"
#include "FileEnumerator.h"
#include "HDFSAccessor.h"
#include "ProgressInfo.h"

HANDLE INVALID_HANDLE = (HANDLE) -1;

tProgressProc gProgressProc;
tRequestProc gRequestProc;
int gPluginNo;

char logPath[MAX_PATH];
size_t pathSize = MAX_PATH;

int FsInit(int PluginNr, tProgressProc pProgressProc, tLogProc pLogProc, tRequestProc pRequestProc)
{
    gProgressProc = pProgressProc;
    gRequestProc = pRequestProc;
    gPluginNo = PluginNr;
#ifdef HDFS_WFX_DEBUG
    Logger::getInstance()->init(true, true, pLogProc, PluginNr);
#else
    Logger::getInstance()->init(true, false, pLogProc, PluginNr);
#endif
    LOGGING("FSInit");

    char javaLauncherPath[MAX_PATH];
    size_t pathSize = MAX_PATH;
//    if (pRequestProc != NULL)
//    {
//        char returnedText[100];
//        strcpy(returnedText, "ReturnedTText");
//        BOOL rv = pRequestProc(PluginNr, 3, "CustomTitle", "CustomText", returnedText, 100);
//        LOGGING("requestProc val %d, message %s", rv, returnedText);
//    }
    JVMState::instance()->initialize(Utilities::getJavaLauncherPath(javaLauncherPath, &pathSize));
    int initialized = HDFSAccessor::instance()->initialize();
    LOGGING("HDFSAccesstor initialization done %d", initialized);

    return 0;
}

HANDLE FsFindFirst(char* Path, WIN32_FIND_DATAA *FindData)
{
    LOGGING("FsFindFirst on path %s", Path);
    memset(FindData, 0, sizeof(WIN32_FIND_DATAA));
    FileEnumerator* fEnum = HDFSAccessor::instance()->getFolderContent(Path);
    HANDLE handle = INVALID_HANDLE;
    if (fEnum != NULL)
    {
        if (fEnum->getNext(FindData))
        {
            handle = fEnum;
        } else
        {
            delete fEnum;
        }

    }
    return handle;
}

BOOL FsFindNext(HANDLE Hdl, WIN32_FIND_DATAA *FindData)
{
    LOGGING("FsFindNext");
    memset(FindData, 0, sizeof(WIN32_FIND_DATAA));
    FileEnumerator* fEnum = (FileEnumerator*) Hdl;
    bool retVal = fEnum->getNext(FindData);
    return retVal;
}

int FsFindClose(HANDLE Hdl)
{
    LOGGING("FsFindClose");
    if (Hdl != NULL && Hdl != INVALID_HANDLE)
    {
        FileEnumerator* fEnum = (FileEnumerator*) Hdl;
        delete fEnum;
        Hdl = NULL;
    }

    return FS_FILE_OK;
}

BOOL FsMkDir(char* Path)
{
    LOGGING("FsMkDir %s", Path);
    return HDFSAccessor::instance()->mkdir(Path);
}

BOOL FsRemoveDir(char* RemoteName)
{
    LOGGING("FsRemoveDir %s", RemoteName);
    return HDFSAccessor::instance()->deletePath(RemoteName);
}

int FsRenMovFile(char* OldName, char* NewName, BOOL Move, BOOL OverWrite, RemoteInfoStruct* ri)
{
    LOGGING("FsRenMovFile oldName %s -> newName %s - Move: %d - Overwrite: %d", OldName, NewName, Move, OverWrite);
    bool success = false;
    if (Move)
    {
        success = HDFSAccessor::instance()->rename(OldName, NewName);
    } else
    {
        success = HDFSAccessor::instance()->copy(OldName, NewName);
    }
    return success ? FS_FILE_OK : FS_FILE_NOTFOUND;
}

int FsGetFile(char* RemoteName, char* LocalName, int CopyFlags, RemoteInfoStruct* ri)
{
    LOGGING("FsGetFile from %s to %s wiht copy flags %d", RemoteName, LocalName, CopyFlags);
    ProgressInfo* progressInfo = new ProgressInfo(RemoteName, LocalName, gProgressProc, gPluginNo);
    bool success = HDFSAccessor::instance()->getFile(RemoteName, LocalName, progressInfo);
    delete progressInfo;
    return success ? FS_FILE_OK : FS_FILE_READERROR;

    //FS_FILE_READERROR, FS_FILE_USERABORT, FS_FILE_NOTFOUND, FS_FILE_NOTSUPPORTED
}

int FsPutFile(char* LocalName, char* RemoteName, int CopyFlags)
{
    LOGGING("FsPutFile Local path %s in HDFS path %s with flags %d", LocalName, RemoteName, CopyFlags);
    ProgressInfo* progressInfo = new ProgressInfo(LocalName, RemoteName, gProgressProc, gPluginNo);
    bool success = HDFSAccessor::instance()->putFile(LocalName, RemoteName, true, progressInfo);
    delete progressInfo;
    return success ? FS_FILE_OK : FS_FILE_WRITEERROR;
}

int FsExecuteFile(HWND MainWin, char* RemoteName, char* Verb)
{
    LOGGING("FsExecuteFile %s verb %s", RemoteName, Verb);
    return -1;
}

BOOL FsDeleteFile(char* RemoteName)
{
    LOGGING("FsDeleteFile %s", RemoteName);
    return HDFSAccessor::instance()->deletePath(RemoteName);
    return 0;
}

BOOL FsSetTime(char* RemoteName, FILETIME *CreationTime, FILETIME *LastAccessTime, FILETIME *LastWriteTime)
{
    LOGGING("FsSetTime %s", RemoteName);
    return 0;
}

BOOL FsDisconnect(char *DisconnectRoot)
{
    LOGGING("FsDisconnect root %s", DisconnectRoot);
    JVMState::instance()->detach();
    return 0;
}

void FsSetDefaultParams(FsDefaultParamStruct* dps)
{
    LOGGING("FsSetDefaultParams %s version %d:%d size %d", dps->DefaultIniName, dps->PluginInterfaceVersionHi, dps->PluginInterfaceVersionLow, dps->size);
}

void FsGetDefRootName(char* DefRootName, int maxlen)
{
#ifdef HDFS_WFX_DEBUG
    Logger::getInstance()->init(true, true);
#else
    Logger::getInstance()->init(true, false);
#endif
    LOGGING("FsGetDefRootName");
    strncpy(DefRootName, "HDFS", maxlen);
}
<commit_msg>temporary remove progress<commit_after>/*
 *    hdfs_wfx.cpp file written and maintained by Calin Cocan
 *    Created on: May 15, 2015
 *
 *    Double Commander
 *   -------------------------------------------------------------------------
 *   WFX plugin for working with HDFS
 *
 *   Based on:
 *     GVFS plugin for Double Commander
 *     Copyright (C) 2009-2010  Koblov Alexander (Alexx2000@mail.ru)
 *
 *     and
 *
 *     GVFS plugin for Tux Commander
 *     Copyright (C) 2008-2009 Tomas Bzatek <tbzatek@users.sourceforge.net>*
 *
 *
 * This work is free: you can redistribute it and/or modify it under the terms of Apache License Version 2.0
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the License for more details.
 * You should have received a copy of the License along with this program. If not, see <http://choosealicense.com/licenses/apache-2.0/>.

 ********************************************************************************************************************* */

#include "wfxplugin.h"
#include <stddef.h>
#include <string.h>
#include "JVMState.h"
#include "gendef.h"
#include "Logger.h"
#include "Utilities.h"
#include "FileEnumerator.h"
#include "HDFSAccessor.h"
#include "ProgressInfo.h"

HANDLE INVALID_HANDLE = (HANDLE) -1;

tProgressProc gProgressProc;
tRequestProc gRequestProc;
int gPluginNo;

char logPath[MAX_PATH];
size_t pathSize = MAX_PATH;

int FsInit(int PluginNr, tProgressProc pProgressProc, tLogProc pLogProc, tRequestProc pRequestProc)
{
    gProgressProc = pProgressProc;
    gRequestProc = pRequestProc;
    gPluginNo = PluginNr;
#ifdef HDFS_WFX_DEBUG
    Logger::getInstance()->init(true, true, pLogProc, PluginNr);
#else
    Logger::getInstance()->init(true, false, pLogProc, PluginNr);
#endif
    LOGGING("FSInit");

    char javaLauncherPath[MAX_PATH];
    size_t pathSize = MAX_PATH;
//    if (pRequestProc != NULL)
//    {
//        char returnedText[100];
//        strcpy(returnedText, "ReturnedTText");
//        BOOL rv = pRequestProc(PluginNr, 3, "CustomTitle", "CustomText", returnedText, 100);
//        LOGGING("requestProc val %d, message %s", rv, returnedText);
//    }
    JVMState::instance()->initialize(Utilities::getJavaLauncherPath(javaLauncherPath, &pathSize));
    int initialized = HDFSAccessor::instance()->initialize();
    LOGGING("HDFSAccesstor initialization done %d", initialized);

    return 0;
}

HANDLE FsFindFirst(char* Path, WIN32_FIND_DATAA *FindData)
{
    LOGGING("FsFindFirst on path %s", Path);
    memset(FindData, 0, sizeof(WIN32_FIND_DATAA));
    FileEnumerator* fEnum = HDFSAccessor::instance()->getFolderContent(Path);
    HANDLE handle = INVALID_HANDLE;
    if (fEnum != NULL)
    {
        if (fEnum->getNext(FindData))
        {
            handle = fEnum;
        } else
        {
            delete fEnum;
        }

    }
    return handle;
}

BOOL FsFindNext(HANDLE Hdl, WIN32_FIND_DATAA *FindData)
{
    LOGGING("FsFindNext");
    memset(FindData, 0, sizeof(WIN32_FIND_DATAA));
    FileEnumerator* fEnum = (FileEnumerator*) Hdl;
    bool retVal = fEnum->getNext(FindData);
    return retVal;
}

int FsFindClose(HANDLE Hdl)
{
    LOGGING("FsFindClose");
    if (Hdl != NULL && Hdl != INVALID_HANDLE)
    {
        FileEnumerator* fEnum = (FileEnumerator*) Hdl;
        delete fEnum;
        Hdl = NULL;
    }

    return FS_FILE_OK;
}

BOOL FsMkDir(char* Path)
{
    LOGGING("FsMkDir %s", Path);
    return HDFSAccessor::instance()->mkdir(Path);
}

BOOL FsRemoveDir(char* RemoteName)
{
    LOGGING("FsRemoveDir %s", RemoteName);
    return HDFSAccessor::instance()->deletePath(RemoteName);
}

int FsRenMovFile(char* OldName, char* NewName, BOOL Move, BOOL OverWrite, RemoteInfoStruct* ri)
{
    LOGGING("FsRenMovFile oldName %s -> newName %s - Move: %d - Overwrite: %d", OldName, NewName, Move, OverWrite);
    bool success = false;
    if (Move)
    {
        success = HDFSAccessor::instance()->rename(OldName, NewName);
    } else
    {
        success = HDFSAccessor::instance()->copy(OldName, NewName);
    }
    return success ? FS_FILE_OK : FS_FILE_NOTFOUND;
}

int FsGetFile(char* RemoteName, char* LocalName, int CopyFlags, RemoteInfoStruct* ri)
{
    LOGGING("FsGetFile from %s to %s wiht copy flags %d", RemoteName, LocalName, CopyFlags);
    ProgressInfo* progressInfo = NULL;//new ProgressInfo(RemoteName, LocalName, gProgressProc, gPluginNo);
    bool success = HDFSAccessor::instance()->getFile(RemoteName, LocalName, progressInfo);
    delete progressInfo;
    return success ? FS_FILE_OK : FS_FILE_READERROR;

    //FS_FILE_READERROR, FS_FILE_USERABORT, FS_FILE_NOTFOUND, FS_FILE_NOTSUPPORTED
}

int FsPutFile(char* LocalName, char* RemoteName, int CopyFlags)
{
    LOGGING("FsPutFile Local path %s in HDFS path %s with flags %d", LocalName, RemoteName, CopyFlags);
    ProgressInfo* progressInfo = NULL;//new ProgressInfo(LocalName, RemoteName, gProgressProc, gPluginNo);
    bool success = HDFSAccessor::instance()->putFile(LocalName, RemoteName, true, progressInfo);
    delete progressInfo;
    return success ? FS_FILE_OK : FS_FILE_WRITEERROR;
}

int FsExecuteFile(HWND MainWin, char* RemoteName, char* Verb)
{
    LOGGING("FsExecuteFile %s verb %s", RemoteName, Verb);
    return -1;
}

BOOL FsDeleteFile(char* RemoteName)
{
    LOGGING("FsDeleteFile %s", RemoteName);
    return HDFSAccessor::instance()->deletePath(RemoteName);
    return 0;
}

BOOL FsSetTime(char* RemoteName, FILETIME *CreationTime, FILETIME *LastAccessTime, FILETIME *LastWriteTime)
{
    LOGGING("FsSetTime %s", RemoteName);
    return 0;
}

BOOL FsDisconnect(char *DisconnectRoot)
{
    LOGGING("FsDisconnect root %s", DisconnectRoot);
    JVMState::instance()->detach();
    return 0;
}

void FsSetDefaultParams(FsDefaultParamStruct* dps)
{
    LOGGING("FsSetDefaultParams %s version %d:%d size %d", dps->DefaultIniName, dps->PluginInterfaceVersionHi, dps->PluginInterfaceVersionLow, dps->size);
}

void FsGetDefRootName(char* DefRootName, int maxlen)
{
#ifdef HDFS_WFX_DEBUG
    Logger::getInstance()->init(true, true);
#else
    Logger::getInstance()->init(true, false);
#endif
    LOGGING("FsGetDefRootName");
    strncpy(DefRootName, "HDFS", maxlen);
}
<|endoftext|>